Array Partition I

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 1:

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

题目意思:将数组每相邻两个数组成对,然后在对在挑出最小值相加,最后返回sum;

思路:把数组按从小到大排好队,然后分别将偶数项相加。

代码如下
 1 class Solution {
 2     public int arrayPairSum(int[] nums) {
 3         Arrays.sort(nums);
 4         int sum=0;
 5         for(int i=0;i<nums.length;i+=2){
 6             sum+=nums[i];
 7         }
 8         return sum;
 9     }
10 }

 

posted @ 2017-10-12 19:24  im.lhc  阅读(114)  评论(0编辑  收藏  举报