题目描述
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
|
|
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]
.
分析
这道题,让我们分隔数组形成两两一对,让每对中较小数的和最大。
若要最大化每对中的较小数之和,那么肯定是没对中两个数字大小越相近也好。因为如果差距过大,而我们只取每对中最小数字,那么较大的那个数就被浪费掉了。因此,我们只需要给数组排序,然后按照顺序的每两个就是一对。取出每对中第一个数字(较小值)累加起来即可。
代码
Swift
|
|
C++
|
|
Java
|
|