Python 1798.py
class Solution:
def getMaximumConsecutive(self, coins: List[int]) -> int:
# simple code but took me a while ...
# upper end of the range where we can make every number
high = 0
for c in sorted(coins):
# if we look at the next coin, we can add c to all those numbers
# that means we can add c to high, c to high - 1, c to high - 2, ...
# in the end we extend our range from high to high + c
# however, if c > high + 1 then there is no way to represent high + 1
if c > high + 1:
break
high += c
return high + 1 # including the zero
Difficulty
and has an acceptance rate of about 64% (40k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
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 computes the length of the longest consecutive integer interval that can be formed using a multiset of coin denominations, assuming each coin can be used at most once. The algorithm proceeds by first arranging the coin values in non-decreasing order and then iteratively extending a reachable range [0, high]. When a gap is encountered-i.e., a coin value exceeds high + 1-the process stops because the next integer cannot be represented. The final answer is high + 1, which includes the value zero as a trivially reachable sum.
Key Steps
Sorting the Coins
for c in sorted(coins):
The loop iterates over the coin values after they have been sorted in ascending order. Sorting guarantees that the algorithm examines smaller denominations before larger ones, which is essential for the greedy extension of the reachable range.
Extending the Reachable Range
high += c
When the current coin c satisfies the condition c <= high + 1, it can be combined with any subset of previously processed coins to produce all sums up to high + c. By adding c to high, the algorithm records the new upper bound of the consecutive interval that is guaranteed to be representable.
Early Termination
if c > high + 1:
break
If a coin value is larger than high + 1, the integer high + 1 cannot be formed with any combination of the processed coins, and no later (larger) coin can fill this gap. The break statement stops further processing, preserving the invariant that all numbers up to high are reachable while high + 1 is not.
Final Result
return high + 1 # including the zero
The method returns high + 1, which represents the count of consecutive integers starting from zero that can be constructed. Zero is always attainable by selecting no coins, so the result includes it automatically.
Edge Cases Handled
When the input list coins is empty, the sorted call yields an empty iterator, the loop body never executes, and high remains zero. Consequently, the function returns 1, correctly indicating that only the sum zero is achievable.
If the list contains a single coin with value 1, the condition c > high + 1 evaluates to 1 > 0 + 1, which is false. The algorithm adds the coin to high, resulting in high = 1, and returns 2, reflecting that both 0 and 1 are reachable.
For a single coin with value greater than 1, such as 5, the condition 5 > 0 + 1 holds true, triggering the early break before any addition to high. The function then returns 1, indicating that only zero can be formed, which aligns with the mathematical expectation.
Duplicate coin values are naturally accommodated because each occurrence is processed independently in the sorted order. The algorithm treats each duplicate as an additional opportunity to extend the reachable range, respecting the “use-once” constraint.
Very large coin values do not cause overflow or incorrect behavior because Python integers have arbitrary precision. The comparison c > high + 1 and the subsequent addition high += c remain valid regardless of magnitude.
Performance Optimizations
The algorithm’s primary optimization is the greedy early-exit condition. By halting as soon as a gap is detected, it avoids unnecessary processing of the remaining (larger) coins, which could be numerous. This early termination reduces the effective work to the smallest prefix of the sorted list that determines the answer.
Sorting the input once, rather than repeatedly searching for the smallest unused coin, ensures that the subsequent linear scan operates on a monotonic sequence. The linear pass over the sorted array performs only constant-time operations per element-comparison, possible break, and addition-resulting in a tight, cache-friendly loop.
Using a single accumulator variable high eliminates the need for auxiliary data structures such as sets or boolean arrays that would otherwise track reachable sums. This minimal memory footprint contributes to faster execution, especially for large input sizes.
ELI5 - Simplified Explanation
Imagine having a collection of toy coins. You want to see how many different dollar amounts you can build by adding these coins together, starting from one dollar up to some total.
To do this, you first put all your coins in a row from the smallest value to the largest value. You start with a range of zero, which is like having an empty piggy bank. As you pick up each coin from your sorted row, you check if you can make the next number you need.
If the new coin is small enough, it fills the gap and lets you reach a new, higher total. You simply add the value of that coin to your current total. This keeps growing your reach, letting you represent every number from one up to that new total.
However, if you pick up a coin that is much larger than your current total plus one, there is a gap you cannot bridge. Because you cannot make that missing number, you have to stop right there. Everything you counted up to that moment is the final amount you can reach. The total you found plus one represents the very next number that you cannot make.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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 | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| shreymehul | C# | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| shreymehul | C# | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 330: Patching Array
Solved On The Same Day
- problem 1935: Maximum Number of Words You Can Type
- problem 722: Remove Comments
- problem 907: Sum of Subarray Minimums
- problem 871: Minimum Number of Refueling Stops
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