Constrained Subsequence Sum
Hard
Topics
Given an integer array nums and an integer target (= k), return the maximum sum of a non-empty subsequence such that for every two consecutive chosen elements at indices i < j, the condition j - i <= target holds.
Example 1
Input: nums = [10,2,-10,5,20], target = 2 Output: 37
Example 2
Input: nums = [-1,-2,-3], target = 1 Output: -1
Example 3
Input: nums = [10,-2,-10,-5,20], target = 2 Output: 23
Constraints
- 1 <= target <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Let dp[i] be the best sum of a valid subsequence that ends at index i. Then dp[i] = nums[i] + max(0, best dp in the window [i-k, i-1]). The max(0, ...) is the option to start fresh at i rather than extend anything.
Written directly that is O(n·k), which at 10⁵ × 10⁵ is far too slow. The inner query is a sliding-window maximum, and the monotonic deque answers it in amortised O(1): hold indices whose dp values are decreasing, drop the front when it falls out of the window, and drop the back while it is dominated by the incoming value.
Dropping the max(0, ...) is the classic mistake — it forces every element to attach to a predecessor. On nums = [-3,-2,1,0] with k = 3 that returns -2 where the answer is 1.
Approach
- Walk
ifrom 0. Pop the deque front while it is older thani - k. - Read the window maximum as
dp[front], or 0 if the deque is empty. - Set
dp[i] = nums[i] + max(0, that)and fold it into the running answer. - Pop the deque back while its
dpis less than or equal todp[i], then pushi.
Dry Run
nums = [10, 2, -10, 5, 20] target = 2
i nums[i] window max dp[i] deque of indices after
0 10 0 10 + max(0, 0) = 10 [0]
1 2 10 2 + max(0, 10) = 12 [1]
2 -10 12 -10 + max(0,12) = 2 [1, 2]
3 5 12 5 + max(0, 12) = 17 [3]
4 20 17 20 + max(0, 17) = 37 [4]
answer max dp = 37 the subsequence is 10, 2, 5, 20
all-negative check: [-1,-2,-3] with k=1 gives -1, the best single elementComplexity
- Time — O(n): every index is pushed once and popped once, so the two inner
whileloops are amortised constant. - Space — O(n) for the
dparray and the deque. The deque alone is O(k); only thedparray forces O(n), and since eachdp[i]is read only withinksteps, a ring buffer of sizek+1brings the total to O(k).
Common Pitfalls
- Omitting
max(0, ...). Verified counterexample:[-3,-2,1,0]withk = 3returns -2 instead of 1, because every element is forced to extend a negative prefix. - Initialising the answer to 0 rather than negative infinity. The subsequence must be non-empty, so an all-negative array has a negative answer and 0 is not achievable.
- Storing
dpvalues in the deque instead of indices, which loses the information needed to expire the front by position. - Expiring with
dq[0] <= i - kinstead of< i - k. The constraint isj - i <= k, so indexi - kis still legal. - Reading this as a subarray problem. Elements may be skipped; only the gap between chosen elements is bounded, which is why it is a DP and not a sliding window over sums.
- Using a heap instead of a deque. It works and is O(n log n), but stale entries must be lazily discarded by index, and the deque gets the same answer in O(n).
Full Solution — all languages
class Solution:
def constrainedSubsetSum(self, nums, target):
from collections import deque
dq = deque()
n = len(nums)
dp = [0] * n
ans = float("-inf")
for i in range(n):
while dq and dq[0] < i - target:
dq.popleft()
best = dp[dq[0]] if dq else 0
dp[i] = nums[i] + max(0, best)
ans = max(ans, dp[i])
while dq and dp[dq[-1]] <= dp[i]:
dq.pop()
dq.append(i)
return ansimport java.util.*;
class Solution {
public int constrainedSubsetSum(int[] nums, int target) {
int n = nums.length;
long[] dp = new long[n];
Deque<Integer> dq = new ArrayDeque<>();
long ans = Long.MIN_VALUE;
for (int i = 0; i < n; i++) {
while (!dq.isEmpty() && dq.peekFirst() < i - target) dq.pollFirst();
long best = dq.isEmpty() ? 0 : dp[dq.peekFirst()];
dp[i] = nums[i] + Math.max(0, best);
ans = Math.max(ans, dp[i]);
while (!dq.isEmpty() && dp[dq.peekLast()] <= dp[i]) dq.pollLast();
dq.addLast(i);
}
return (int)ans;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int constrainedSubsetSum(vector<int>& nums, int target) {
int n = nums.size();
vector<long long> dp(n, 0);
deque<int> dq;
long long ans = LLONG_MIN;
for (int i = 0; i < n; i++) {
while (!dq.empty() && dq.front() < i - target) dq.pop_front();
long long best = dq.empty() ? 0 : dp[dq.front()];
dp[i] = nums[i] + max(0LL, best);
ans = max(ans, dp[i]);
while (!dq.empty() && dp[dq.back()] <= dp[i]) dq.pop_back();
dq.push_back(i);
}
return (int)ans;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var constrainedSubsetSum = function(nums, target) {
const n = nums.length;
const dp = new Array(n).fill(0);
const dq = [];
let head = 0, ans = -Infinity;
for (let i = 0; i < n; i++) {
while (head < dq.length && dq[head] < i - target) head++;
const best = head < dq.length ? dp[dq[head]] : 0;
dp[i] = nums[i] + Math.max(0, best);
ans = Math.max(ans, dp[i]);
while (dq.length > head && dp[dq[dq.length - 1]] <= dp[i]) dq.pop();
dq.push(i);
}
return ans;
};