leetcode 1218. Longest Arithmetic Subsequence of Given Difference

insert image description here

Given the array arr and a difference difference, extract the longest subsequence without disturbing the order of numbers in arr, so that the difference between every two adjacent elements in the sequence is difference. Find the length of the longest subsequence that satisfies the condition
.

Ideas:

DP

Because the difference difference is fixed, every time an element is extracted, the element before it is also fixed.
For example, the current element is arr[ i ], then the element before it must be arr[ i ] - difference.
So the sequence length up to arr[ i ] is also fixed.

Only need to count the subsequence length up to arr[ i ].
Make a note of the maximum of these lengths.

The dp array can use a hashMap to save (arr[ i ], the length of the subsequence up to arr[ i ]),
or an array.

(1)HashMap

    public int longestSubsequence(int[] arr, int difference) {
    
    
        Map<Integer,Integer> dp = new HashMap<>();
        int n = arr.length;
        int res = 0;

        for(int i = 0; i < n; i++) {
    
    
            dp.put(arr[i], dp.getOrDefault(arr[i]-difference, 0)+1);
            res = Math.max(res, dp.get(arr[i]));
        }

        return res;
    }

(2) Arrays
directly subscript elements, which is faster.
In order to save storage space, the length of the dp array is the maximum value of arr - the minimum value + 1.
But it should be noted that the subscript in dp is arr[ i ] - min. And Not the subscript i of arr.

    public int longestSubsequence(int[] arr, int difference) {
    
    
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int res = 1;

        for(int num : arr) {
    
    
            min = Math.min(min, num);
            max = Math.max(max, num);
        }

        int[] dp = new int[max-min+1];
        for(int i = 0; i < arr.length; i++) {
    
    
            int cur = arr[i] - min;
            int pre = cur - difference;
            if(pre >= 0 && pre < dp.length) {
    
    
                dp[cur] = dp[pre] + 1;
                if(dp[cur] > res) res = dp[cur];
            } else {
    
    
                dp[cur] = 1;
            }
        }
        return res;
    }

Guess you like

Origin blog.csdn.net/level_code/article/details/131715889