Python 1425.py
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
best = [ 0 ] # descending order of best recent indices
high = [ nums[0] ]
for i, n in enumerate(nums):
if i == 0:
continue
high.append(max(n, high[best[0]] + n))
# remove worse choices
while best and high[best[-1]] < high[-1]:
best.pop()
# remove outdated
if best and best[0] + k <= i:
best.pop(0)
best.append(i)
return max(high)
Difficulty
and has an acceptance rate of about 56% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Heap (Priority Queue)
- Monotonic Queue
- Queue
- Sliding Window
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the constrained subset sum problem by iterating through the input list nums while maintaining two auxiliary structures: high, which records the best achievable sum ending at each index, and best, a deque-like list that stores indices of recent positions in decreasing order of their corresponding high values. By keeping only the most promising candidates within the sliding window of size k, the algorithm can compute the global maximum without revisiting earlier elements.
Initialization
At the start the algorithm creates a list best containing a single element 0. This list is intended to hold indices in descending order of their high values, with the most promising index at the front. The list high is seeded with the first element of nums, representing the best sum that can be obtained ending at position 0.
best = [0] # stores indices, front is most promising
high = [nums[0]] # best sum ending at each index, start with first element
The loop then begins enumerating nums. The first iteration (i == 0) is skipped because the initial values have already been accounted for.
Main Loop
For each subsequent element n at position i, the algorithm first computes a candidate sum that either starts a new subsequence with n alone or extends the best subsequence ending at the most promising recent index (best[0]). This candidate is appended to high.
high.append(max(n, high[best[0]] + n))
The max call ensures that the algorithm correctly handles the edge case where extending a previous subsequence would produce a smaller sum than starting fresh with the current element. This covers scenarios such as negative numbers or isolated positive spikes.
Updating the best Structure - Removing Worse Choices
After a new high value is added, the algorithm purges indices from the tail of best whose associated high values are strictly less than the newly added high. This step guarantees that best remains monotonic decreasing with respect to high, so the front of the list always points to the index with the largest achievable sum within the current window.
while best and high[best[-1]] < high[-1]:
best.pop()
By eliminating dominated indices, the algorithm avoids unnecessary comparisons in later iterations, which is a key performance optimization. The structure behaves like a monotonic queue, providing amortized constant-time updates.
Updating the best Structure - Removing Outdated Indices
The algorithm also discards indices that have fallen outside the allowed distance k. If the oldest index in best plus k is less than or equal to the current index i, that index can no longer contribute to any future subsequence and is removed from the front.
if best and best[0] + k <= i:
best.pop(0)
This check handles the edge case where k is smaller than the distance between the current position and the earliest stored index, ensuring that the sliding window constraint is respected throughout the computation.
Adding the Current Index
After cleaning up both dominated and stale entries, the current index i is appended to best. At this point best again satisfies the invariant of holding indices in decreasing order of their high values and all of them lie within the last k positions.
best.append(i)
Final Result
When the loop finishes, the algorithm returns the maximum value stored in high. Because high contains the best sum ending at each index, the global maximum corresponds to the optimal constrained subset sum.
return max(high)
Edge Cases Handled
The code gracefully manages several edge conditions:
- A single-element input list: the early
continueskips the loop andhighalready contains the correct answer. - Negative numbers: the
maxoperation when extending a subsequence versus starting anew prevents the accumulation of detrimental values. - Small window size
k(includingk == 1): the outdated-index removal ensures that only the immediate predecessor can be used, effectively reducing the problem to a simple maximum of individual elements. - Large
krelative to the list length: the outdated-index condition never triggers, allowing the algorithm to consider the entire prefix as a valid window.
Performance Optimizations
The most notable optimization is the use of a monotonic deque pattern (best) to keep track of the best candidate indices. By discarding dominated entries immediately and by removing stale entries as soon as they exit the window, each index is inserted and removed at most once. This yields linear-time behavior despite the nested while loop, because the total number of pop operations across the entire execution does not exceed the number of elements in nums.
Another subtle optimization is the avoidance of explicit slicing or copying of sub-arrays. All operations are performed in-place on the high and best lists, minimizing memory overhead and cache pressure.
Overall, the implementation combines a sliding-window approach with a monotonic queue to achieve an efficient solution that respects the problem constraints while handling a variety of input edge cases.
ELI5 - Simplified Explanation
Think of the numbers in the list like a line of hopping stones across a little stream. Each stone has a number on it. Some numbers are big and happy, and some are small or even negative. The goal is to hop from stone to stone to collect the biggest possible total sum, but there is a rule. You cannot jump over more than k stones at once.
The code starts by keeping track of the best possible total you can have at each stone. Imagine a backpack where you store the biggest sum you have found so far while moving along. For every new stone, the code looks back at the previous stones within reach. It decides whether to add the current stone to a previous total or just start fresh with the number on the current stone if that is better.
As the code moves forward, it keeps a small list of the best paths it has seen recently. It behaves like a tiny robot that is very smart about remembering which path gave it the most points. If a path becomes too old to jump to, or if a path is clearly worse than a newer one, the robot removes it to keep things organized. This way, the robot always knows which stone to jump to next to keep the score as high as possible. By the time it reaches the end of the line of stones, it has looked at all the possibilities and found the highest total available.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | Java | C++ | Python | TS | ||
| WalkCCC | Java | C++ | Python | ||||
| leetcode.ca | Java | C++ | Go | Python | TS | ||
| Progiez | Java | C++ | Python | ||||
| github | charles-wangkai | Java | |||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| gouthampradhan | Java | ||||||
| JoshCrozier | JS | ||||||
| keineahnung2345 | C++ | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ | ||||||
| gouthampradhan | Java | ||||||
| JoshCrozier | JavaScript | ||||||
| keineahnung2345 | C++ | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1217: Minimum Cost to Move Chips to The Same Position
- problem 1221: Split a String in Balanced Strings
- problem 1323: Maximum 69 Number
- problem 1710: Maximum Units on a Truck
- problem 969: Pancake Sorting
- problem 991: Broken Calculator
- problem 1605: Find Valid Matrix Given Row and Column Sums
- problem 630: Course Schedule III
- problem 2147: Number of Ways to Divide a Long Corridor
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality