【LeetCode】561. Array Partition I

35 篇文章 0 订阅
26 篇文章 0 订阅

Problem: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.

题目:一个2n数组,任意组合为n对(ai,bi),求Min(a,b)和,求出可能组合中使求和最大。


思路:本来一开始没太懂意思,但是研究题意找出了规律。

首先排序,再每两个相邻两个划分为一组,即(i,i+1),i-(1,3,5...),再求i为奇数位数的和。即为最后解的结果。

解完题仔细一想,题意中是找出最大和,如果每对中数都是最小的,大一点的在其余对中,才会有可能取值到,这样求和才比较大。

代码:

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

}



看提交有点amazing!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值