码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode.561. Array Partition I

时间:2019-01-06 10:45:54      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:input   min   xpl   长度   class   tput   解决   其他   NPU   

题目的大意为给定一个长度为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;
    }

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

LeetCode.561. Array Partition I

标签:input   min   xpl   长度   class   tput   解决   其他   NPU   

原文地址:https://www.cnblogs.com/xusong95/p/10226975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!