Longest Arithmetic Subsequence of Given Difference Problem
Description
LeetCode Problem 1218.
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.
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.
Example 3:
Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Constraints:
1 <= arr.length <= 10^5-10^4 <= arr[i], difference <= 10^4
Solution
Approach: Dynamic Programming with a Hash Map
Because the difference is fixed, a subsequence that ends with the value x must have x - difference right before it. So the longest one ending at x is one more than the longest one ending at the value x - difference somewhere earlier in the array.
Scan the array once and keep a hash map best from a value to the length of the longest such subsequence ending with that value so far:
best[x] = best.get(x - difference, 0) + 1
If the same value appears again later, overwriting its entry is right: the later occurrence can extend everything the earlier one could, and it is at least as long. The case difference = 0 works too, since the update then reads best[x] itself and counts how often x has appeared.
The answer is the largest value ever stored in the map.
Complexity: O(n) time and O(n) extra space for the map.
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
best = {} # value -> length of the longest such subsequence ending with that value
ans = 0
for x in arr:
best[x] = best.get(x - difference, 0) + 1
ans = max(ans, best[x])
return ans