Problem 2178

Abstract / Summary

Given an even integer, find the maximum number of positive even integers that sum to it.

Note

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

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
20 lines | 561 bytes | submitted February 8, 2024 | GitHub   13% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (90k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
  • Greedy
  • Math
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 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.

written by openai gpt

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.

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 = 7.5 | μ = 7.35 | σ = 1.00

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 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#
25 links | 12 authors | 9 languages

Videos

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

Solved On The Same Day

5 solutions   February 8, 2024

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