Constrained Subsequence Sum
Problem Statement
You are given an integer array nums and a number k.
Pick a non-empty subsequence of nums (some elements, kept in their original order). There is one rule: for any two elements you pick next to each other in the subsequence, at positions i < j, the gap must be small: j − i ≤ k. In other words, you may never skip more than k − 1 elements in a row between two picks.
Return the largest possible sum of such a subsequence. It can start and end anywhere.
An integer array nums of length n, and an integer k.
A single integer: the maximum sum.
Pick [10, 2, 5, 20]. Skipping -10 makes a gap of 2 (from index 1 to 3), which is allowed.
The subsequence can't be empty. The best you can do is pick just -1.
Pick [10, -2, -5, 20]. You have to keep -2 and -5 to get from 10 to 20 without a gap bigger than 2.
- • 1 ≤ k ≤ n ≤ 10^5
- • −10^4 ≤ nums[i] ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
dp[i] = nums[i] + max(0, best of the last k dp values), found by a loop
Keep (dp, index) in a max-heap; skip tops that are too far back
Deque of indices with decreasing dp; dp[i] = nums[i] + max(0, dp[front])
Fill dp left to right. For each i, loop over the last k indices to find the best dp[j], take max(0, that), and add nums[i]. The answer is the largest dp[i].
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.