Maximum Split of Positive Even Integers LeetCode solution in Java

1
class Solution {
2
public List<Long> maximumEvenSplit(long finalSum) {
3
List<Long> res = new ArrayList<Long>();
4
// odd sum cannot be divided into even numbers
5
if (finalSum % 2 != 0) {
6
return res;
7
}
8
// Greedy approach, try to build the total sum using minimum unique even nos
9
long currNum = 2;
10
long remainingSum = finalSum;
11
// as long as we can add subtract this number from remaining sum
12
while (currNum <= remainingSum) {
13
res.add(currNum);
14
remainingSum -= currNum; // reducing remaining sum
15
currNum += 2; // next even number
16
}
17
// now, remaining sum cannot be fulfilled by any larger even number
18
// so extract the largest even number we added to the last index of res, and make it even larger
19
// by adding this current remaining sum
20
// add remaining sum to the last element
21
long last = res.remove(res.size() - 1);
22
res.add(last + remainingSum);
23
return res;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0