[LeetCode] Longest Arithmetic Subsequence of Given Difference

1218. Longest Arithmetic Subsequence of Given Difference

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.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int longestSubsequence(vector<int>& arr, int difference) {
unordered_map<int, int> m;
int res = 0;
for(auto& n : arr) {
res = max(res, m[n] = max(m[n], m[n-difference] + 1));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/01/PS/LeetCode/longest-arithmetic-subsequence-of-given-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.