題目地址:
https://www.lintcode.com/problem/array-partition-i/description
給定一個長度爲的數組,要求將其分爲個數對,其中,使得最大。返回這個最大的和。
從小到大排序後將第個數相加即可。代碼如下:
import java.util.Arrays;
public class Solution {
/**
* @param nums: an array
* @return: the sum of min(ai, bi) for all i from 1 to n
*/
public int arrayPairSum(int[] nums) {
// Write your code here
if (nums == null || nums.length == 0) {
return 0;
}
int res = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i += 2) {
res += nums[i];
}
return res;
}
}
時間複雜度,空間。
算法正確性證明參考https://blog.csdn.net/qq_46105170/article/details/103776402。