Maximum Split of Positive Even Integers — Medium Problem & Solution
Split finalSum into the maximum number of unique positive even integers that add up to it, and return them in increasing order.
- Difficulty: Medium
- Topics: Math, Greedy
- Asked at: Amazon, Google, Zoho
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Split finalSum into the maximum number of unique positive even integers that add up to it, and return them in increasing order.
If no such split exists, return an empty array.
Example 1
Input: finalSum = 12
Output: [2,4,6]
Explanation: Three distinct even numbers; no split into four exists.
Example 2
Input: finalSum = 7
Output: []
Explanation: An odd total can never be a sum of even numbers.
Example 3
Input: finalSum = 28
Output: [2,4,6,16]
Explanation: The greedy takes 2, 4, 6 and 8 and then folds the leftover 8 into the last term.
Constraints
1 <= finalSum <= 1000000000
How to solve Maximum Split of Positive Even Integers
Take the smallest even numbers in order for as long as they fit; the leftover is then folded into the last term, which keeps the values distinct and the count maximal.
Approach
- Return empty for an odd
finalSum. - Take
2, 4, 6, …while the next value is at most the remaining total. - Add the remaining total to the last value taken.
Why it works
Greedily taking the smallest available even numbers maximises how many fit — using any larger value instead would consume budget that could have supported more terms. The leftover after stopping is even and strictly smaller than the next unused value, so adding it to the last term keeps that term the largest and still distinct from all the others.
Complexity
- Time —
O(sqrt(finalSum)) - Space —
O(sqrt(finalSum))
Pitfalls
- Appending the leftover as a new term can duplicate a value already taken.
- The odd case must be handled before the loop.
- The greedy takes
2 · kterms up to roughlysqrt(finalSum), so the output stays small.
Reference solution
Python
from typing import List
def maximumEvenSplit(finalSum: int) -> List[int]:
if finalSum % 2 != 0:
return []
out = []
rem, i = finalSum, 2
while i <= rem:
out.append(i)
rem -= i
i += 2
out[-1] += rem
return outJavaScript
var maximumEvenSplit = function(finalSum) {
if (finalSum % 2 !== 0) return [];
var out = [];
var rem = finalSum, i = 2;
while (i <= rem) { out.push(i); rem -= i; i += 2; }
out[out.length - 1] += rem;
return out;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.