目录

描述

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.

Example 1:

Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].

Constraints:

  • 1<=arr.length<=1051 <= arr.length <= 10^5
  • 104<=arr[i],difference<=104-10^4 <= arr[i],difference <= 10^4

题意

  • 找寻给定差值的等差子序列

思路

  • 类比 最长递增子序列,思考以每个数结尾的等差子序列长度,因为插值固定,前驱即为当前值减去插值,我们可以用字典保存以当前值结尾的等差子序列长度,状态转移方程为:dp[num]=dp[numdifference]+1dp[num] = dp[num - difference] + 1

代码

class Solution {
public:
    int longestSubsequence(vector<int>& arr, int difference) {
        unordered_map<int,int> dp;
        int ans = 0;
        for(auto &num:arr){
            dp[num] = dp[num - difference] + 1;
            ans = max(ans,dp[num]);
        }
        return ans;
    }
};
func longestSubsequence(arr []int, difference int) (ans int) {
    dp := map[int]int{}
    for _,v := range arr{
        dp[v] = dp[v - difference] + 1
        if dp[v] > ans{
            ans = dp[v]
        }
    }
    return
}