Maximum Split of Positive Even Integers Problem
Description
LeetCode Problem 2178.
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.
- For example, given
finalSum = 12, the following splits are valid (unique positive even integers summing up tofinalSum):(12),(2 + 10),(2 + 4 + 6), and(4 + 8). Among them,(2 + 4 + 6)contains the maximum number of integers. Note thatfinalSumcannot be split into(2 + 2 + 4 + 4)as all the numbers should be unique.
Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Example 1:
Input: finalSum = 12
Output: [2,4,6]
Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8).
(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].
Note that [2,6,4], [6,2,4], etc. are also accepted.
Example 2:
Input: finalSum = 7
Output: []
Explanation: There are no valid splits for the given finalSum.
Thus, we return an empty array.
Example 3:
Input: finalSum = 28
Output: [6,8,2,12]
Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24).
(6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].
Note that [10,2,4,12], [6,2,4,16], etc. are also accepted.
Constraints:
1 <= finalSum <= 10^10
Solution
Approach: Greedy
If finalSum is odd, it cannot be a sum of even integers, so return an empty array.
Otherwise, to use as many distinct parts as possible, take the smallest even numbers 2, 4, 6, ... one by one while the remaining sum is still at least the next number. When the next even number no longer fits, add whatever is left to the last part you took. That keeps all parts distinct (the last one only grows) and even.
Complexity: time O(sqrt(finalSum)), since about sqrt(finalSum) parts are produced; space O(1) besides the answer.
class Solution:
def maximumEvenSplit(self, finalSum: int) -> List[int]:
if finalSum & 1:
return []
ans = []
i = 2
while i <= finalSum:
finalSum -= i
ans.append(i)
i += 2
ans[-1] += finalSum
return ans