2178. Split into the sum of the largest number of positive and even numbers

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

Input: finalSum = 12
 Output: [2,4,6]
 Explanation: Here are some splits that fit the requirement: (2 + 10),(2 + 4 + 6) and(4 + 8) 。
(2 + 4 + 6) is the largest number of integers, 3, so we return [2,4,6].
[2,6,4] , [6,2,4] etc. are also feasible solutions.

 If finalSum is odd, return directly;

 If finalSum is an even number, finalSum can be split in the order of 2, 4, 6, ... until the last positive integer cannot be split. At this point, add finalSum to the last number.

class Solution {
    public List<Long> maximumEvenSplit(long finalSum) {
        List<Long> list = new ArrayList<>();
        if (finalSum % 2 != 0) return list;
        for(long i = 2; i <= finalSum; i+=2){
            list.add(i);
            finalSum -= i;
        }
        list.add(list.remove(list.size()-1)+finalSum);
        return list;


    }
}

 

 

 

Guess you like

Origin blog.csdn.net/d905133872/article/details/131583024