https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/
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
.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
1 <= arr.length <= 10^5
-10^4 <= arr[i], difference <= 10^4
算法思路:
使用unordered_map存储数组中数值的角标,然后使用dp数组记录,dp[i] : 以角标i对应元素x结尾的数组的Longest Arithmetic Subsequence of Given Difference个数。
class Solution {
public:
int longestSubsequence(vector<int>& arr, int difference) {
int n = arr.size();
unordered_map<int, int> um;
vector<int> dp(n, 1);
int res = 0;
for(int i = 0; i < n; i++) {
um[arr[i]] = i;
if(um.find(arr[i] - difference) != um.end()) dp[i] = 1 + dp[um[arr[i] - difference]];
res = max(res, dp[i]);
}
return res;
}
};
在上述方法中,使用角标然后去map找到对应元素x,不如直接改造dp为unordered_map,让dp记录当前x可最长等差数列个数。
注:对于stl中的unordered_map,如果不存在某个元素,使用[]会创建并舒适化为0,比如-1不存在,现在使用dp[-1],则创建dp[-1],并初始化为0,如果想查找一下,如果不存在不想创建它,使用find或者count函数。
class Solution {
public:
int longestSubsequence(vector<int>& arr, int d) {
unordered_map<int, int> dp;
int res = 0;
for(int& x : arr) res = max(res, dp[x] = dp[x - d] + 1);
return res;
}
};