# [C++] Clean Code - 1 sentence explanation

• In short, the sum of all number is fixed, to maximize the sum of smaller group, you want to minimize the diff of the sum of 2 groups.
And the best way to do that is to pair the numbers that are next to each other in sorted order.
C++

``````class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int sum = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i += 2) {
sum += nums[i];
}

return sum;
}
};
``````

Java

``````class Solution {
public int arrayPairSum(int[] nums) {
int sum = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i += 2) {
sum += nums[i];
}

return sum;
}
}
``````

• can you tell me why this works? i cannot understand problem yet. too short explain..

• I think this post explained pretty well regard the idea:
https://discuss.leetcode.com/topic/87206/java-solution-sorting-and-rough-proof-of-algorithm

In short, the sum of all number is fixed, to maximize the sum of smaller group, you want to minimize the diff of the sum of 2 groups.
And the best way to do that is to pair the numbers that are next to each other in sorted order.

• @alexander thanks. It helped.

• @alexander
tq for ur suggestion alex

• My code is same to you lol

• My solution is 99.9% just like yours. Still trying to understand the fastest solution, it's a bit complicated.

• i use same solution;but rank is 15%;too slow,so sad

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.