Longest Subsequence With Decreasing Adjacent Difference - Problem
Given an array of integers nums, find the length of the longest subsequence where the absolute differences between consecutive elements form a non-increasing sequence.
For a subsequence seq₀, seq₁, seq₂, ..., seqₘ, the condition is:|seq₁ - seq₀| ≥ |seq₂ - seq₁| ≥ ... ≥ |seqₘ - seqₘ₋₁|
Example: In array [4, 2, 1, 3, 5], subsequence [4, 1, 3] has differences [3, 2] which is non-increasing, giving us a length of 3.
Your task is to return the maximum possible length of such a subsequence.
Input & Output
example_1.py — Basic Case
$
Input:
[4, 2, 1, 3]
›
Output:
3
💡 Note:
The longest valid subsequence is [4, 1, 3] with absolute differences [3, 2]. Since 3 ≥ 2, this forms a valid non-increasing sequence of differences.
example_2.py — All Same Differences
$
Input:
[1, 3, 5, 7, 9]
›
Output:
5
💡 Note:
The entire array [1, 3, 5, 7, 9] has differences [2, 2, 2, 2]. Since all differences are equal (2 ≥ 2 ≥ 2 ≥ 2), the entire sequence is valid.
example_3.py — Single Element
$
Input:
[5]
›
Output:
1
💡 Note:
A single element always forms a valid subsequence of length 1, as there are no differences to check.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
- The array may contain duplicate elements
Visualization
Tap to expand
Understanding the Visualization
1
Identify Elements
Start with the input array and consider each element as a potential part of our subsequence
2
Calculate Differences
For each pair of elements, calculate the absolute difference that would be used in our subsequence
3
Build DP State
Track the longest valid subsequence ending at each position with each possible last difference
4
Extend Subsequences
For each new position, extend previous subsequences where the difference constraint is satisfied
5
Find Maximum
The answer is the maximum length across all valid subsequences
Key Takeaway
🎯 Key Insight: Use DP to track the longest valid subsequence ending at each position with each possible last difference, allowing efficient extension of subsequences while maintaining the non-increasing constraint.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code