Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.

A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [10,2,-10,5,20], k = 2
Output: 37
💡 Note: The subsequence is [10, 2, 5, 20]. Distance between consecutive elements: 2-0=2≤k, 3-1=2≤k, 4-3=1≤k. Sum = 10+2+5+20 = 37
Example 2 — Constraint Limitation
$ Input: nums = [4,-1,2,3], k = 2
Output: 6
💡 Note: The subsequence is [4, 2, 3]. We skip -1. Distance: 2-0=2≤k, 3-2=1≤k. Sum = 4+2+3 = 9. Wait, let's recalculate: actually [4,3] gives 7, [2,3] gives 5, single element max is 4. Best is actually [4,2,3] = 9. But we need to check constraint carefully.
Example 3 — Single Element
$ Input: nums = [-1,-2,-3], k = 1
Output: -1
💡 Note: All elements are negative. The best subsequence is just [-1] with sum -1

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Constrained Subsequence Sum Problem102-1052001234k = 2 (max distance between consecutive elements in subsequence)d=1≤2d=2≤2d=1≤2Selected subsequence: [10, 2, 5, 20]Distance constraints: 1-0=1≤2, 3-1=2≤2, 4-3=1≤2 ✓Maximum Sum: 10 + 2 + 5 + 20 = 37
Understanding the Visualization
1
Input
Array [10,2,-10,5,20] with constraint k=2
2
Process
Find subsequence where consecutive elements are at most k positions apart
3
Output
Maximum sum 37 from subsequence [10,2,5,20]
Key Takeaway
🎯 Key Insight: Use dynamic programming with sliding window maximum to efficiently find the best previous position within distance k
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
25.4K Views
Medium Frequency
~30 min Avg. Time
890 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