1218. Longest Arithmetic Subsequence of Given Difference

;  |     Back to Homepage   |     Back to Code List


class Solution {
    public int longestSubsequence(int[] arr, int difference) {
        Map<Integer, Integer> map = new HashMap<>();
        int max = 1;
        for (int item : arr) {
            int prev = item - difference;
            if (map.get(prev) == null) {
                map.put(item, 1);
            } else {
                map.put(item, map.get(prev) + 1);
                max = Math.max(max, map.get(item));
            }
        }

        return max;
    }
}