[LeetCode]561. Array Partition I (陣列分割槽 1)
阿新 • • 發佈:2019-02-05
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.
題目大意:
給定一個長度為2n(偶數)的陣列,分成n個小組,返回每組中較小值的和sum,使sum儘量大
Example 1:
Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4.
Note:
- n is a positive integer, which is in the range of [1, 10000].
- All the integers in the array will be in the range of [-10000, 10000].
思路:
- 先排序,將相鄰兩個數分為一組,每組較小數都在左邊,求和即可
演算法分析:
檢視英文版請點選上方
- 假設對於每一對i,bi >= ai。
- 定義Sm = min(a1,b1)+ min(a2,b2)+ … + min(an,bn)。最大的Sm是這個問題的答案。由於bi >= ai,Sm = a1 + a2 + … + an。
- 定義Sa = a1 + b1 + a2 + b2 + … + an + bn。對於給定的輸入,Sa是常數。
- 定義di = | ai - bi |。由於bi >= ai,di = bi-ai, bi = ai+di。
- 定義Sd = d1 + d2 + … + dn。
- 所以Sa = a1 + (a1 + d1) + a2 + (a2 + d2) + … + an + (an + di) = 2Sm + Sd , 所以Sm =(Sa-Sd)/ 2。為得到最大Sm,給定Sa為常數,需要使Sd儘可能小。
- 所以這個問題就是在陣列中找到使di(ai和bi之間的距離)的和儘可能小的對。顯然,相鄰元素的這些距離之和是最小的。
程式碼如下:
// https://leetcode.com/problems/array-partition-i/#/description原題
//https://discuss.leetcode.com/topic/87206/java-solution-sorting-and-rough-proof-of-algorithm
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int res = 0;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size(); i+=2){
res += nums[i];
}
return res;
}
};
int main()
{
Solution a;
int num[4] = {1, 4, 3, 2};
int numLength = sizeof(num) / sizeof(num[0]);
vector<int> nums(num, num+numLength);
cout << a.arrayPairSum(nums) << endl;
return 0;
}