Problem Description
Given an integer array and a target difference, find the length of the longest subsequence in the array such that the difference between adjacent elements is exactly the given value. A subsequence can skip elements but must maintain the original order.
Key Insights
- Use dynamic programming to track the longest arithmetic subsequence ending at each number.
- Use a hash table (dictionary or map) to efficiently retrieve and update the length of subsequences.
- For each element, check if there exists a previous element equal to the current element minus the difference.
- The answer is the maximum subsequence length tracked while processing the array.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array, since we process each element once. Space Complexity: O(n), used by the hash table to store subsequence lengths for each unique element.
Solution
The solution uses a hash table (or dictionary/map) to keep track of the longest arithmetic subsequence that ends at a particular number. For every number in the array, the algorithm checks if there is a subsequence ending with the number that is exactly "difference" less. If so, the current number is added to that subsequence, increasing its length by 1. Otherwise, a new subsequence starting with the number is considered with length 1. The maximum subsequence length is updated accordingly throughout the iteration.