leetcode每日一题-1218:最长定差子序列

leetcode每日一题-1218:最长定差子序列

链接

最长定差子序列



题目

在这里插入图片描述



分析

简单的逻辑分析问题,因为是等差序列,所以只需要遍历数组,然后每次以当前位置为结尾的位置,然后再加上之前的所有值即可,同时动态维护最大值,就能得到答案.



代码

C++

class Solution {
public:
    int longestSubsequence(vector<int>& arr, int d) {
        int res = 0;
        // 记录下当前位置之前的所有情况
        unordered_map<int,int> m;
        for(int x : arr)
        {
            // 以当前位置为结尾,所以+1,然后计算和前面可以安排的序列长度
            m[x] = 1 + m[x - d];
            // 动态维护最大值
            res = max(res, m[x]);
        }
        return res;
    }
};

java

class Solution {
    
    
    public int longestSubsequence(int[] arr, int difference) {
    
    
        int ans = 0;
        Map<Integer, Integer> dp = new HashMap<Integer, Integer>();
        for (int v : arr) {
    
    
            dp.put(v, dp.getOrDefault(v - difference, 0) + 1);
            ans = Math.max(ans, dp.get(v));
        }
        return ans;
    }
}

作者:LeetCode-Solution

おすすめ

転載: blog.csdn.net/qq_45826803/article/details/121169423