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: 9
💡 Note: The subsequence is [4, 2, 3] at indices [0, 2, 3]. Distance between consecutive elements: 2-0=2≤k, 3-2=1≤k. Sum = 4+2+3 = 9
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 INPUT nums array: 10 i=0 2 i=1 -10 i=2 5 i=3 20 i=4 Constraint: k = 2 j - i <= k for consecutive Valid Jump Range: i i+1 i+2 i+3 Green = reachable from i Red = too far (j-i > k) nums = [10, 2, -10, 5, 20] k = 2 ALGORITHM (DP) 1 Define DP State dp[i] = max sum ending at i 2 Transition dp[i] = nums[i] + max(0, max(dp[i-k:i])) 3 Use Monotonic Deque Track max in window of k 4 Return max(dp) Answer = max of all dp values DP Computation: i: 0 1 2 3 4 num: 10 2 -10 5 20 dp: 10 12 2 17 37 dp[0]=10 dp[1]=2+10=12 dp[2]=-10+12=2 dp[3]=5+12=17 dp[4]=20+17=37 FINAL RESULT Optimal Subsequence: 10 i=0 + 2 i=1 + 5 i=3 + 20 i=4 Constraint Check: 1-0=1 <= 2 OK 3-1=2 <= 2 OK 4-3=1 <= 2 OK Skipped: nums[2] = -10 (negative, reduces sum) Output: 37 Key Insight: Use Dynamic Programming with a Monotonic Deque (sliding window maximum) to efficiently track the best previous dp value within k steps. The deque maintains candidates in decreasing order, giving O(1) access to maximum. Total time complexity: O(n). Space complexity: O(n). TutorialsPoint - Constrained Subsequence Sum | Dynamic Programming with Monotonic Deque
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