Longest Arithmetic Subsequence - Problem
Given an array nums of integers, find the length of the longest arithmetic subsequence.
An arithmetic subsequence is a sequence where the difference between consecutive elements is constant. For example, [2, 4, 6, 8] has a common difference of 2.
Important: A subsequence maintains the relative order of elements from the original array, but elements don't need to be contiguous. You can skip elements as needed.
Example: In array [3, 6, 9, 12], the entire array forms an arithmetic subsequence of length 4 with difference 3.
Input & Output
example_1.py โ Basic Case
$
Input:
[3, 6, 9, 12]
โบ
Output:
4
๐ก Note:
The entire array forms an arithmetic sequence with common difference 3: [3, 6, 9, 12]. Length = 4.
example_2.py โ Mixed Sequences
$
Input:
[9, 4, 7, 2, 10]
โบ
Output:
3
๐ก Note:
The longest arithmetic subsequence is [4, 7, 10] with common difference 3, or [9, 7, 2] with difference -2. Both have length 3.
example_3.py โ No Long Sequence
$
Input:
[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
- -500 โค nums[i] โค 500
- All elements in nums are integers
Visualization
Tap to expand
Understanding the Visualization
1
Identify Patterns
Look for pairs of elements that could start an arithmetic sequence
2
Calculate Intervals
For each pair, determine the common difference (musical interval)
3
Extend Sequences
Find additional elements that continue each pattern
4
Track the Longest
Remember the longest arithmetic sequence found
Key Takeaway
๐ฏ Key Insight: Dynamic programming helps us efficiently track all possible arithmetic patterns by remembering what sequences we've already built, avoiding redundant work.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code