Constrained Subsequence Sum Problem
Description
LeetCode Problem 1425.
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.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Solution
Approach: Dynamic Programming + Monotonic Deque
Let f[i] be the largest sum of a valid subsequence that ends at index i. The element before nums[i] in it must sit in the window i - k .. i - 1, or nums[i] starts the subsequence on its own:
f[i] = nums[i] + max(0, max(f[j] for i - k <= j < i))
The max(0, ...) is what lets a subsequence start fresh: when every f[j] in the window is negative, adding one would only hurt. The answer is the largest f[i], which handles the all-negative case (Example 2) by picking the single largest number.
Computing the window maximum by scanning is O(nk), too slow for n = k = 105. This is the classic sliding-window maximum, solved with a deque of indices whose f values decrease from front to back:
- Before computing
f[i], drop the front index if it is more thankpositions behindi. The front is then the window's maximum. - After computing
f[i], pop indices from the back while theirfis<= f[i]: they are older and not larger, so they can never be the maximum again. Then pushi.
Complexity: O(n) time, since each index enters and leaves the deque once, and O(n) extra space.
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [0] * n # f[i]: best sum of a valid subsequence ending at i
q = deque() # indices in the window, with f decreasing from front to back
ans = nums[0]
for i, x in enumerate(nums):
if q and i - q[0] > k:
q.popleft()
f[i] = x + max(0, f[q[0]] if q else 0)
ans = max(ans, f[i])
while q and f[q[-1]] <= f[i]:
q.pop()
q.append(i)
return ans