Constrained Subsequence Sum - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code