Skip to content

1218. Longest Arithmetic Subsequence of Given Difference 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int longestSubsequence(vector<int>& arr, int difference) {
    int ans = 0;
    unordered_map<int, int> lengthAt;

    for (const int a : arr) {
      if (const auto it = lengthAt.find(a - difference); it != lengthAt.cend())
        lengthAt[a] = it->second + 1;
      else
        lengthAt[a] = 1;
      ans = max(ans, lengthAt[a]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int longestSubsequence(int[] arr, int difference) {
    int ans = 0;
    Map<Integer, Integer> lengthAt = new HashMap<>();

    for (final int a : arr) {
      lengthAt.put(a, lengthAt.getOrDefault(a - difference, 0) + 1);
      ans = Math.max(ans, lengthAt.get(a));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def longestSubsequence(self, arr: list[int], difference: int) -> int:
    ans = 0
    lengthAt = {}

    for a in arr:
      lengthAt[a] = lengthAt.get(a - difference, 0) + 1
      ans = max(ans, lengthAt[a])

    return ans