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 Difference INPUT Array: nums 4 idx 0 7 idx 1 2 idx 2 8 idx 3 Possible Subsequences: [4,7,8]: |7-4|=3, |8-7|=1 3 >= 1 [OK] len=3 [4,2,8]: |2-4|=2, |8-2|=6 2 < 6 [FAIL] [7,2]: |2-7|=5 len=2 ALGORITHM STEPS 1 Initialize DP HashMap dp[val][diff] = max length 2 For each element Check all previous elements 3 Compute abs diff Find valid extensions 4 Update DP state Track max subsequence DP HashMap State dp[4][0] = 1 (start) dp[7][3] = 2 (4-->7, d=3) dp[2][5] = 2 (7-->2, d=5) dp[8][1] = 3 (7-->8, d=1) 3 >= 1: valid chain! FINAL RESULT Longest Valid Subsequence 4 7 8 |7-4|=3 |8-7|=1 3 >= 1 [OK] Decreasing: Valid! Output 3 Length of longest valid subsequence [4, 7, 8] Key Insight: Use HashMap dp[value][diff] to track maximum subsequence length ending at 'value' with last difference 'diff'. For each new element, only consider previous states with diff >= current diff. This ensures non-increasing absolute differences. Time: O(n^2 * maxDiff), Space: O(n * maxDiff). TutorialsPoint - Longest Subsequence With Decreasing Adjacent Difference | Optimized DP with HashMap
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