561. Array PartitionI

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个组,取出每个组中的最小值,求这些最小值之和的最大值

思路:这个题只要你将这个数组在纸上写出来就能很容易的找到方法,
如何让sum 最大化呢,我们想一下,如果是两个数字,一个很小,一个很大,这样的话,
取一个小的数字,就浪费了那个大的数字。所以我们要使每一对的两个数字尽可能接近,这样得到的值就尽可能的最大化

例如 n1 n2 n3 n4 n5 n6 n7 n8 …..

其中和为最大值的取值为:n1+n3+n5+n7….+2n(n-1)
和为最小值的取值为:n1+n2+n3+n4…+n(n-1)

 public int arrayPairSum(int[] nums) {

        Arrays.sort(nums);
        int sum=0;
        for (int i =0;i<nums.length;i=i+2){
            sum+=nums[i];
        }
        return sum;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值