Directory link:
Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog
GitHub synchronous brushing project:
https://github.com/September26/java-algorithms
Link to the original title: Likou
describe:
gives you an integer finalSum
. Please split it into the sum of several positive even numbers that are different from each other , and the number of positive even numbers split out is the largest .
- Let's say, for you
finalSum = 12
, then these splits are satisfactory (distinct positive even numbers and the sum isfinalSum
):(2 + 10)
,(2 + 4 + 6)
and(4 + 8)
. Among them,(2 + 4 + 6)
contains the largest number of integers. Note thatfinalSum
it cannot be split into(2 + 2 + 4 + 4)
, because the split integers must be different from each other.
Please return an integer array, which means splitting the integer into the largest number of positive even arrays. If there is no way to finalSum
split it, you return an empty array. You can return these integers in any order.
Example 1:
Input: finalSum = 12 Output: [2,4,6] Explanation: Here are some splits that meet the requirements: sum(2 + 10),
(2 + 4 + 6)
((4 + 8) 。
2 + 4 + 6) is the maximum number of integers, the number is 3, so we return [2,4 ,6]. [2,6,4] , [6,2,4] etc. are also feasible solutions.
Example 2:
Input: finalSum = 7 Output: [] Explanation: There is no way to split finalSum. So return empty array.
Example 3:
Input: finalSum = 28 Output: [6,8,2,12] Explanation: Here are some splits that meet the requirements: The sum has the largest number of integers, which is 4, so we return [6,8,2,12(2 + 26),
(6 + 8 + 2 + 12)
](4 + 24) 。
(6 + 8 + 2 + 12)
. [10,2,4,12] , [6,2,4,16] etc. are also feasible solutions.
hint:
1 <= finalSum <= 1010
Problem-solving ideas:
/**
* 2178. Split into the sum of the largest number of positive and even numbers
* Problem-solving ideas:
* First, judge whether it is an even number, if it is an odd number, return empty directly.
* Then, judge finalSum>=2*i+2, if the condition is met, it means that the remaining value is enough to put i and i+2, then finalSum -= i and list.push_back(i);
* Otherwise, the description is not enough, then directly add finalSum and jump out of the loop
*/
code:
class Solution2178
{
public:
vector<long long> maximumEvenSplit(long long finalSum)
{
vector<long long> list;
if (finalSum % 2 != 0)
{
return list;
}
for (long long i = 2;; i = i + 2)
{
// 保证下一轮还够
if (finalSum - i >= i + 2)
{
finalSum -= i;
list.push_back(i);
continue;
}
// 如果下一轮不够,则直接使用剩余所有值
list.push_back(finalSum);
break;
}
return list;
}
};