LeetCode·Daily Question·2178. Split into the sum of the largest number of positive and even numbers·Greedy

Author: Xiao Xun
Link: https://leetcode.cn/problems/maximum-split-of-positive-even-integers/solutions/2332925/tan-xin-zhu-shi-chao-ji-xiang-xi-by- xun-zoioi/
Source: The copyright of LeetCode
belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

topic

 

example

 

train of thought

Title -> Given an integer t, divide it into n even numbers, and return a set with the largest n.

Require:

  1. There can be no duplicate values ​​between n even numbers
  2. After n even numbers, for the original integer t

The title requires that the sum of even numbers after splitting is equal to the original number t, and after even numbers must be even numbers, so if t is an odd number, you can directly return empty.

Secondly, we want to split into as many even numbers as possible, and we should split into the smallest number of even numbers as possible. Try splitting sequentially from the smallest even integer 2 until the remaining value is less than or equal to the largest even integer currently being split.

At this point, we have split into as many even numbers as possible, and it is impossible to split more even numbers that are different from each other.

If the remaining finalSum after splitting is greater than zero at this time, add this value to the largest even integer, so as to ensure that all numbers are different from each other and the sum is equal to finalsum.

Code comments are super detailed

the code


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
long long* maximumEvenSplit(long long finalSum, int* returnSize){
    *returnSize = 0;
    if (finalSum & 1) return NULL;//判断奇偶
    long long *ans = (long long *)malloc(sizeof(long long) * (sqrt(finalSum) + 1));//初始化
    for (int i = 2; i <= finalSum; i += 2) {//从小枚举偶数
        ans[(*returnSize)++] = i;//记录集合
        finalSum -= i;//利用 - 代替 + 来判断结束
    }
    //将剩余不足以再开辟一个新位置的偶数和入最大值,保证唯一
    ans[(*returnSize)-1] += finalSum;
    return ans;
}   

作者:小迅
链接:https://leetcode.cn/problems/maximum-split-of-positive-even-integers/solutions/2332925/tan-xin-zhu-shi-chao-ji-xiang-xi-by-xun-zoioi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/m0_64560763/article/details/131573082