# 561. Array Partition I

Given an array of **2n** integers, your task is to group these integers into **n** pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

**Example 1:**<br>

```
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
```

**Note:**<br>

1. **n** is a positive integer, which is in the range of \[1, 10000].
2. All the integers in the array will be in the range of \[-10000, 10000].

{% hint style="info" %}
假設所有數的總和是S\_all = a1 + b1 + a2 + b2 + ... + an + bn，而所求答案為S\_m = min(a1, b1) + min(a2 , b2) + ... + min(an, bn)，每一組pair之間的距離為di = |ai - bi|，所有的di相加為S\_d = d1 + d2 + ... + dn。可以推得S\_all = 2 \* S\_m + S\_d，整理一下可以得到S\_m = (S\_all - S\_d) / 2，所以只要想辦法讓S\_d最小，就可以得到最大的S\_m。經過觀察讓S\_d最小的方法就是讓每組pair之間沒有重疊的區域，所以讓每組(ai, bi)相鄰。
{% endhint %}

```cpp
int arrayPairSum(vector<int>& nums) { // time: O(nlogn); space: O(1)
    sort(nums.begin(), nums.end());
    int res = 0;
    for (int i = 0; i < nums.size(); i += 2) {
        res += nums[i];
    }
    return res;
}
```
