561. Array Split I
A given length of 2n
the array of integers nums
, your task is divided into a number of these n
pairs, e.g. (a1, b1), (a2, b2), ..., (an, bn)
, from such 1
to n
the min(ai, bi)
sum of the maximum.
Return the maximum sum.
Example 1:
输入:nums = [1,4,3,2]
输出:4
解释:所有可能的分法(忽略元素顺序)为:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
所以最大总和为 4
Example 2:
输入:nums = [6,2,6,5,1,2]
输出:9
解释:最优的分法为 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9
prompt:
1 <= n <= 10^4
nums.length == 2 * n
-10^4 <= nums[i] <= 10^4
Method 1: Sort
Problem-solving ideas
- After sorting, take the even number and accumulate
Reference Code
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int ret = 0;
for (int i = 0; i < nums.length; i += 2) {
ret += nums[i];
}
return ret;
}
Results of the