Constrained Subsequence Sum — LeetCode 1425 Python Solution
- Problem
- #1425
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [10,2,-10,5,20], k = 2
- Output
- 37
- Explanation
- The subsequence is [10, 2, 5, 20].
Python solution
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q = deque([0])
n = len(nums)
f = [0] * n
ans = -inf
for i, x in enumerate(nums):
while i - q[0] > k:
q.popleft()
f[i] = max(0, f[q[0]]) + x
ans = max(ans, f[i])
while q and f[q[-1]] <= f[i]:
q.pop()
q.append(i)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1425. Constrained Subsequence Sum is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1425. Constrained Subsequence Sum?
- LeetCode 1425. Constrained Subsequence Sum is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1425. Constrained Subsequence Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1425. Constrained Subsequence Sum?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1425. Constrained Subsequence Sum cover?
- LeetCode 1425. Constrained Subsequence Sum is tagged Queue, Array, Dynamic Programming, Sliding Window, Monotonic Queue and Heap (Priority Queue) on LeetCode.