# [C++] Clean Code

• 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.

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

return summin;
}
};
``````

• 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.

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