Longest Arithmetic Subsequence Problem
Description
LeetCode Problem 1027.
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.
Note that:
- A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
- A sequence
seqis arithmetic ifseq[i + 1] - seq[i]are all the same value (for0 <= i < seq.length - 1).
Example 1:
Input: nums = [3, 6, 9, 12]
Output: 4
Explanation: The whole array is already an arithmetic sequence with a common difference of 3, so the longest arithmetic subsequence is [3, 6, 9, 12], of length 4.
Example 2:
Input: nums = [9, 4, 7, 2, 10]
Output: 3
Explanation: The longest arithmetic subsequence is [4, 7, 10] (indices 1, 2, 4), with a common difference of 3. There is no arithmetic subsequence of length 4.
Example 3:
Input: nums = [20, 1, 15, 3, 10, 5, 8]
Output: 4
Explanation: The longest arithmetic subsequence is [20, 15, 10, 5] (indices 0, 2, 4, 5), with a common difference of -5.
Constraints:
2 <= nums.length <= 15000 <= nums[i] <= 500
Solution
Approach: Dynamic Programming Over (End, Difference)
An arithmetic subsequence is fixed by its last element and its common difference. Let f[i][d] be the length of the longest arithmetic subsequence that ends at nums[i] with difference d. Every element alone is a sequence of length 1, so all entries start at 1.
For each i, try every earlier index k < i as the element just before nums[i]. The difference is d = nums[i] - nums[k], and we can extend the best sequence ending at k with that difference:
f[i][d] = max(f[i][d], f[k][d] + 1)
The answer is the largest value seen, and at least 2, since any two elements form an arithmetic sequence.
Since 0 <= nums[i] <= 500, the difference is between -500 and 500. Adding 500 maps it to an index in [0, 1000], so each row of f can be a plain array of 1001 entries instead of a hash map. Don't forget the negative differences: in [20, 1, 15, 3, 10, 5, 8] the answer [20, 15, 10, 5] has difference -5.
Complexity: O(n2 + n * D) time and O(n * D) space, where D = 1001 is the number of possible differences.
class Solution:
def longestArithSeqLength(self, nums: List[int]) -> int:
n = len(nums)
# f[i][d + 500]: length of the longest arithmetic subsequence ending at nums[i] with difference d
f = [[1] * 1001 for _ in range(n)]
best = 2 # any two elements form one
for i in range(1, n):
for k in range(i):
d = nums[i] - nums[k] + 500 # shift so a negative difference is a valid index
f[i][d] = max(f[i][d], f[k][d] + 1)
best = max(best, f[i][d])
return best