Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
A subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.
For each number in the array, check if there is a previous number in the arithmetic sequence (current number minus difference). Use a hash map to store the length of the longest subsequence ending at each number. Update the map as you iterate.
Iterate through the array. For each element, set its subsequence length to one more than the length of the subsequence ending at num - difference (or 1 if none exists). Track the maximum length found.
classSolution {
public:int longestSubsequence(vector<int>& arr, int difference) {
unordered_map<int, int> dp;
int ans =0;
for (int num : arr) {
dp[num] = dp[num - difference] +1;
ans = max(ans, dp[num]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
funclongestSubsequence(arr []int, differenceint) int {
dp:= make(map[int]int)
ans:=0for_, num:=rangearr {
dp[num] = dp[num-difference] +1ifdp[num] > ans {
ans = dp[num]
}
}
returnans}
1
2
3
4
5
6
7
8
9
publicintlongestSubsequence(int[] arr, int difference) {
Map<Integer, Integer> dp =new HashMap<>();
int ans = 0;
for (int num : arr) {
dp.put(num, dp.getOrDefault(num - difference, 0) + 1);
ans = Math.max(ans, dp.get(num));
}
return ans;
}
1
2
3
4
5
6
7
8
9
funlongestSubsequence(arr: IntArray, difference: Int): Int {
val dp = mutableMapOf<Int, Int>()
var ans = 0for (num in arr) {
dp[num] = (dp[num - difference] ?:0) + 1 ans = maxOf(ans, dp[num]!!)
}
return ans
}
1
2
3
4
5
6
7
8
classSolution:
deflongestSubsequence(self, arr: list[int], difference: int) -> int:
dp = {}
ans =0for num in arr:
dp[num] = dp.get(num - difference, 0) +1 ans = max(ans, dp[num])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::HashMap;
impl Solution {
pubfnlongest_subsequence(arr: Vec<i32>, difference: i32) -> i32 {
letmut dp = HashMap::new();
letmut ans =0;
for&num in&arr {
let len = dp.get(&(num - difference)).copied().unwrap_or(0) +1;
dp.insert(num, len);
ans = ans.max(len);
}
ans
}
}