Constrained Subsequence Sum

Hard

Topics
ArrayDynamic ProgrammingQueueSliding WindowHeapMonotonic Queue

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

10021-10253204
Input:  nums = [10,2,-10,5,20], target = 2
Output: 37

Example 2

-10-21-32
Input:  nums = [-1,-2,-3], target = 1
Output: -1

Example 3

100-21-102-53204
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

  1. Walk i from 0. Pop the deque front while it is older than i - k.
  2. Read the window maximum as dp[front], or 0 if the deque is empty.
  3. Set dp[i] = nums[i] + max(0, that) and fold it into the running answer.
  4. Pop the deque back while its dp is less than or equal to dp[i], then push i.

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 element

Complexity

  • Time — O(n): every index is pushed once and popped once, so the two inner while loops are amortised constant.
  • Space — O(n) for the dp array and the deque. The deque alone is O(k); only the dp array forces O(n), and since each dp[i] is read only within k steps, a ring buffer of size k+1 brings the total to O(k).

Common Pitfalls

  • Omitting max(0, ...). Verified counterexample: [-3,-2,1,0] with k = 3 returns -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 dp values in the deque instead of indices, which loses the information needed to expire the front by position.
  • Expiring with dq[0] <= i - k instead of < i - k. The constraint is j - i <= k, so index i - k is 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 ans
SensAI
Beta
Tap the mic to stop voice mode