[Google] LeetCode 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): (12)
, (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.
Solution
为了求得最长长度的答案,显然应该从最小的偶数 \(st=2\) 开始,每次 \(+2\). 但是如果 \(f-st\le st\) 说明不能再减了,因为比 \(st\) 小的偶数都已经用过了,所以此时直接将 \(f\) 加入答案即可。
点击查看代码
class Solution {
private:
vector<long long> ans;
public:
vector<long long> maximumEvenSplit(long long finalSum) {
if(finalSum%2)return ans;
long long st = 2;
while(finalSum){
if(finalSum-st<=st){
ans.push_back(finalSum);break;
}
ans.push_back(st);
finalSum-=st; st+=2;
}
return ans;
}
};