Longest Arithmetic Subsequence - Problem
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).
Input & Output
Example 1 — Basic Arithmetic Sequence
$
Input:
nums = [3,6,9,12]
›
Output:
4
💡 Note:
The entire array forms an arithmetic subsequence with common difference 3: [3,6,9,12]. Length = 4.
Example 2 — Multiple Arithmetic Subsequences
$
Input:
nums = [9,4,7,2,10]
›
Output:
3
💡 Note:
The longest arithmetic subsequences are [4,7,10] with difference 3, and [9,7,2] with difference -3. Both have length 3.
Example 3 — No Long Arithmetic Sequence
$
Input:
nums = [20,1,15,3,10,5,8]
›
Output:
4
💡 Note:
The longest arithmetic subsequence is [20,15,10,5] with common difference -5. Length = 4.
Constraints
- 2 ≤ nums.length ≤ 1000
- 0 ≤ nums[i] ≤ 500
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Given array with various numbers
2
Find Differences
Calculate differences between all pairs
3
Build Sequences
Extend arithmetic sequences with same difference
Key Takeaway
🎯 Key Insight: Use dynamic programming to track the longest arithmetic sequence ending at each position for every possible common difference
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code