HardNo. 1425
Constrained Subsequence Sum — LeetCode 1425 Python Solution
- Pattern
- Sliding Window
- Topics
- Queue, Array, Dynamic Programming, Sliding Window, Monotonic Queue, Heap (Priority Queue)
- 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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 1687 | Delivering Boxes from Storage to Ports | Hard |
| 1696 | Jump Game VI | Medium |
| 2944 | Minimum Number of Coins for Fruits | Medium |
| 0918 | Maximum Sum Circular Subarray | Medium |
| 2407 | Longest Increasing Subsequence II | Hard |
| 0413 | Arithmetic Slices | Medium |
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.