[LeetCode] Maximum Split of Positive Even Integers

2178. Maximum Split of Positive Even Integers

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 to finalSum): (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<long long> maximumEvenSplit(long long finalSum) {
if(finalSum == 0 or (finalSum & 1)) return {};
long long sum = 0, start = 2;
vector<long long> res;
while(sum + start <= finalSum) {
res.push_back(start);
sum += start;
start += 2;
}
if(sum == finalSum)
return res;
long long req = finalSum - sum;
res.back() += req;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/20/PS/LeetCode/maximum-split-of-positive-even-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.