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:

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:

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

假設所有數的總和是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)相鄰。

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;
}

Last updated

Was this helpful?