1 题目
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
2 尝试解
2.1 分析
给定一个数组arr,要求返回相邻元素差值为difference的最长子序列。
令dp[i]表示以arr[i]结尾的最长子序列,则dp[i] = 1+max[dp[k] (for k in range(i) && arr[k]-arr[i]==difference)]。即向前搜索,直到找到与当前元素差值为difference的元素,再其基础上加一即可。但是这样的复杂度在O(N)~O(N^2)之间。可以用map<arr[i],count>代替dp[i],map[arr[i]] = map[arr[i] - difference]+1。其中arr[i]-difference不在map中时,返回0。
2.2 代码
class Solution {
public:
int longestSubsequence(vector<int>& arr, int difference) {
unordered_map<int,int> record;
int result = 0;
for(auto num : arr){
record[num] = 1+record[num-difference];
result = max(record[num],result);
}
return result;
}
};
最长等差子序列

本文介绍了一种高效求解最长等差子序列的算法。针对给定数组和差值,利用哈希表优化动态规划过程,实现O(n)时间复杂度内解决问题。通过实例解析,展示了算法的具体应用。
290

被折叠的 条评论
为什么被折叠?



