Python 2178.py
class Solution:
def maximumEvenSplit(self, finalSum: int) -> List[int]:
if finalSum & 1 or finalSum == 0:
return []
# 2,4,6,8,10,...
result = [ 2 ]
last = total = 2
while total < finalSum:
last += 2
total += last
result.append(last)
# adjust last two numbers if too large
if total > finalSum:
total -= result.pop()
total -= result.pop()
result.append(finalSum - total)
return result
Difficulty
and has an acceptance rate of about 60% (90k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- Greedy
- Math
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 a list of distinct even integers whose sum equals a given positive even number finalSum. The algorithm constructs the smallest possible even numbers in ascending order, then, if the cumulative sum overshoots the target, it readjusts the last two elements to achieve the exact total while preserving distinctness.
Input Validation
if finalSum & 1 or finalSum == 0:
return []
The first conditional checks two edge conditions. The bitwise & 1 test determines whether finalSum is odd; an odd target cannot be expressed as a sum of even numbers, so the function returns an empty list. The second condition catches the case where finalSum is zero, for which no positive even numbers exist, also resulting in an empty list. By handling these scenarios up front, the rest of the logic can assume a positive even input.
Building the Sequence
result = [2]
last = total = 2
while total < finalSum:
last += 2
total += last
result.append(last)
The algorithm starts with the smallest even integer, 2, and records both the most recent even number (last) and the running sum (total). Inside the loop, last is incremented by 2 to obtain the next even integer, which is then added to total. The new even number is appended to result. This process repeats until the cumulative sum meets or exceeds finalSum. Because each iteration adds the next larger even integer, the list remains strictly increasing and all elements stay distinct.
Adjusting Excess
if total > finalSum:
total -= result.pop()
total -= result.pop()
result.append(finalSum - total)
When the loop terminates, total may be greater than the desired sum. In that case, the algorithm removes the last two numbers from result using pop(), subtracting their values from total. The remaining deficit (finalSum - total) is then appended as a single even number. Since the removed numbers were the two largest distinct evens added so far, the replacement value is guaranteed to be larger than the previous element in the list and smaller than the removed numbers, preserving both the distinctness and the ascending order of the sequence.
Edge Cases Handled
The code explicitly addresses three categories of inputs that could otherwise break the logic. An odd finalSum is rejected because the sum of even numbers can never be odd. A zero finalSum yields an empty list because no positive even numbers can sum to zero. When the cumulative sum exceeds the target after the loop, the adjustment step ensures the final list still satisfies the sum requirement without introducing duplicate values. The adjustment also works when only a single even number is needed; in that scenario the loop never runs, and the initial list [2] is either returned directly (if finalSum equals 2) or corrected by the adjustment block.
Performance Considerations
The algorithm builds the result in a single forward pass, incrementally generating each even integer without recomputing previous values. By maintaining last and total as running variables, it avoids repeated summations over the list, which keeps the execution time proportional to the number of elements produced. The use of pop() to discard the last two entries is an O(1) operation on Python lists, and the final append() also runs in constant time. Consequently, the method scales efficiently with the size of the output list, allocating only the necessary storage for the distinct even numbers.
ELI5 - Simplified Explanation
Imagine you have a big pile of building blocks and you want to share them into smaller towers that are all even numbers. An even number is just any number you can share into two equal groups, like two, four, six, or eight. If the total number of blocks you start with is an odd number, it is impossible to make every little tower an even number, so you would just have an empty space instead.
To start building, take the smallest even number, which is two, and put it in a line. Then keep adding the next even number, like four, then six, then eight, and keep going as long as the total pile of blocks is still smaller than the final number you want. You are basically building a staircase of even numbers.
Sometimes, when you keep adding those even blocks, the last tower you add makes the total pile grow bigger than the number you were aiming for. When that happens, take the last two towers you built away. Then, take all the blocks that were in those two towers and mush them together into one new, bigger even number that fits perfectly. That way, all the towers are still even and they all add up to exactly the final number you wanted.
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 | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | C# | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| martianoff | Scala | |||||||||
| suxrobGM | C# | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| martianoff | Scala | |||||||||
| suxrobGM | C# |
Videos
Solved On The Same Day
- problem 2169: Count Operations to Obtain Zero
- problem 2176: Count Equal and Divisible Pairs in an Array
- problem 2121: Intervals Between Identical Elements
- problem 2171: Removing Minimum Number of Magic Beans
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