1. 程式人生 > >LeetCode.561. Array Partition I

LeetCode.561. Array Partition I

題目的大意為給定一個長度為2n的陣列,把陣列分為n對,使從1到n的min(ai,aj)的總和最大。

比如:

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

拿到這道題,發現排序後比較好解決。

可以發現排序後相鄰兩個元素分組,把奇數位置的元素相加即為所求。

    public  int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int sum = 0;
        for (int i = 0; i < nums.length; i += 2) {
           sum += nums[i];
        }
        return sum;
    }

也有其他更好的方法,正在探索當中。