29
loading...
This website collects cookies to deliver better user experience
Input: nums = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Input: nums = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Input: nums = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
2 <= nums.length <= 1000
0 <= nums[i] <= 500
1 8 15
is an AP as 1 (+7) 8 (+7) 15
, we have a difference of 7 and so if I were to ask you what number would come next - what would you say?Also did you notice an interesting fact here - in a sorted list 1 + 15 = 2 x 8
-> the middle number when doubled is equal to the sum of its neighbours! DO NOT FORGET THIS 😉
-1 2 5 8
is a valid AP5 9 1
is a valid AP = 1 5 9
5 4 9 1
has a valid AP subsequence -> 1 5 9
9 4 7 2 10
2 4 7 9 10
-> can you see the AP Subsequence ?4 7 10
- here the length is 3 and the difference is also 31 2 14 15 16 27 29 30 43
diff = 14 [1 15 29]
diff = 14 [1 15 29 43]
diff = 13 [1 14 27]
diff = 14 [2 16 30]
1 15 29 43
public int longestArithSeqLength(int[] nums) {
int size = nums.length;
// Stores the length of sequences having same difference
Map<Integer, Map<Integer, Integer>> dp = new HashMap<>();
// Stores the resultant length
int res = 2;
// Iterate over the array
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
// our dp key is diff
int diff = nums[j] - nums[i];
// here we store the pair of last index which gives us max difference
Map<Integer, Integer> temp = new HashMap<>();
// Update length of subsequence
if (dp.containsKey(diff)) {
temp = dp.get(diff);
if (temp.containsKey(i)) {
temp.put(j, temp.get(i) + 1);
}
}
temp.putIfAbsent(j, 2);
dp.put(diff, temp);
res = Math.max(res, temp.get(j));
}
}
return res;
}
j=4 -> 9-4 -> 5, (3, 2) (4, 2)this is interesting we already have 5 as key, but when we picked the pair we don't have 2nd index as key - so we added a new pair for value set
[2,7][4,9]
j=4 -> 9-7 -> 2, (2, 2) (4, 2)
j=5 -> 10-7 -> 3, (3, 2) (5, 3)` this is interesting we already have 5 as key, so we will update its existing length to +1