1087. Longest Arithmetic Subsequence
2026/1/12大约 1 分钟约 337 字
1087. Longest Arithmetic Subsequence
难度: Medium
题目描述
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.
Note that:
- A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
- A sequence
seqis arithmetic ifseq[i + 1] - seq[i]are all the same value (for0 <= i < seq.length - 1).
Example 1:
Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= nums.length <= 10000 <= nums[i] <= 500
解题思路
代码实现
解决方案
java
class Solution {
public int longestArithSeqLength(int[] nums) {
int minv = Arrays.stream(nums).min().getAsInt();
int maxv = Arrays.stream(nums).max().getAsInt();
int max =0;
int diff = maxv - minv;
for (int d = -diff; d <= diff; ++d) {
max = Math.max(max,longestSubsequence2(nums,d));
}
return max;
}
public int longestSubsequence2(int[] arr, int difference) {
int ans = 0;
Map<Integer,Integer> dp = new HashMap<>();
for(int v:arr){
dp.put(v,dp.getOrDefault(v-difference,0)+1);
ans = Math.max(ans,dp.get(v));
}
return ans;
}
}