Longest Subsequence With Decreasing Adjacent Difference - Problem

You are given an array of integers nums. Your task is to find the length of the longest subsequence seq of nums, such that the absolute differences between consecutive elements form a non-increasing sequence of integers.

In other words, for a subsequence seq₀, seq₁, seq₂, ..., seqₘ of nums, we need:

|seq₁ - seq₀| ≥ |seq₂ - seq₁| ≥ ... ≥ |seqₘ - seqₘ₋₁|

Return the length of such a subsequence.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,7,2,8]
Output: 3
💡 Note: One valid subsequence is [4,7,2] with differences [3,5]. Since 3 ≤ 5 is false, we need [7,4,2] with differences [3,2] where 3 ≥ 2 ✓. Actually, [4,2,8] gives differences [2,6] which is invalid. The longest valid is [7,2] with length 2, but [4,7,2,8] checking all: [4,7] diff=3, [7,2,8] diffs=[5,6] invalid. Best is [4,7,8] with diffs=[3,1] where 3≥1 ✓, giving length 3.
Example 2 — Decreasing Differences
$ Input: nums = [10,5,3,2]
Output: 4
💡 Note: The subsequence [10,5,3,2] has differences [5,2,1]. Since 5 ≥ 2 ≥ 1, this forms a valid non-increasing sequence of differences. The entire array can be used, giving length 4.
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: A single element forms a valid subsequence of length 1 (no differences to check).

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Longest Subsequence With Decreasing Adjacent Difference4728Input: [4, 7, 2, 8]478Valid Subsequence: [4, 7, 8]|7-4| = 3|8-7| = 13 ≥ 1 ✓Output: Length = 3
Understanding the Visualization
1
Input
Array of integers [4,7,2,8]
2
Process
Find subsequence where |diff₁| ≥ |diff₂| ≥ ... ≥ |diffₙ|
3
Output
Length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Use dynamic programming to track subsequences by their last two elements and extend only when differences decrease
Asked in
Google 15 Meta 12 Amazon 8
30.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen