LeetCode561 Array Partition I

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

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

样例

1
2
3
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).

思路

将$2n$个元素两两分组($a_1$, $b_1$), ($a_2$, $b_2$), …, ($a_n$, $b_n$) ,使得这$n$个分组中最小值之和最大。

贪心题,将数组元素从小到大排序,然后相邻的两个元素分为一组。

可以这样考虑,假设元素$a_1$是数组中最小的元素,那么和$a_1$同一组的元素对答案是没有贡献的,因此,应该找到剩下的元素中值最小的和$a_1$匹配。以此类推,可以得出贪心的策略。

代码

1
2
3
4
5
6
7
8
9
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
for (int i = 0; i < nums.size(); i += 2) ans += nums[i];
return ans;
}
};
分享到 评论