LeetCode 1218 Longest Arithmetic Subsequence of Given Difference 哈希表HashMap
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.
Solution
用一个 Map \(dp\) 来保存以每一个数字结尾的最长子序列,转移方程:
\[dp[arr[i]] = dp[arr[i]-\text{diff}]+1
\]
点击查看代码
class Solution {
private:
unordered_map<int,int> dp;
public:
int longestSubsequence(vector<int>& arr, int difference) {
int n =arr.size();
int ans=0;
for(int i=0;i<n;i++){
dp[arr[i]] = dp[arr[i]-difference]+1;
ans = max(ans, dp[arr[i]]);
}
return ans;
}
};