Problem Description
Given an array of integers, the goal is to find the length of the longest arithmetic subsequence in the array. A subsequence is derived from the original array by deleting some or no elements without changing the order. An arithmetic sequence means that the differences between consecutive elements are the same.
Key Insights
- Use dynamic programming where dp[i][diff] represents the length of the longest arithmetic subsequence ending at index i with difference diff.
- For every pair of indices (j, i) with j < i, compute the difference diff = nums[i] - nums[j].
- If there exists a subsequence ending at j with the same difference, extend it; otherwise, start a new subsequence with length 2.
- Finally, keep track of the maximum subsequence length encountered.
Space and Time Complexity
Time Complexity: O(n^2) where n is the number of elements in the array. Space Complexity: O(n^2) in the worst case due to storing differences for each index.
Solution
We iterate over the array with a nested loop. For each pair (j, i), we calculate the difference diff = nums[i] - nums[j] and update our dp array: if there is an entry dp[j][diff], then dp[i][diff] = dp[j][diff] + 1; otherwise, dp[i][diff] is set to 2 (since any two numbers form an arithmetic sequence). The answer is the maximum value in our dp structure. We use a hash table (dictionary) for each index to store the counts of arithmetic subsequences by their common difference.