Problem 1425

Abstract / Summary

Given a list and a limit on how many times each number can be picked, find the maximum sum of a subsequence where no number is chosen more than allowed.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
20 lines | 602 bytes | submitted November 28, 2023 | GitHub   21% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 continue skips the loop and high already contains the correct answer.
  • Negative numbers: the max operation when extending a subsequence versus starting anew prevents the accumulation of detrimental values.
  • Small window size k (including k == 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 k relative 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.08 | σ = 1.82

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
23 links | 12 authors | 6 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   November 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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