LeetCode-Easy-Java——Array Partition I

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

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].
题目要求:给定一个包含2n个整数的数组,把这2n个数分成n对,每对数可以表示为(a1, b1), (a2, b2), ..., (an, bn) ,要求使这n对数中每对数的最小值的和最大。有点绕,看例子还比较容易理解,如果有疑问可以评论留言呐。

解决思路:我觉得算是利用贪心算法的一种。为了让最后的和(sum)最大,所以肯定希望较大值都被加进来。我们先对数组进行一个排序,变为递增序列[a0, a1, a2, a3, ..., a2n-1],其中a2n-1是最大值,a0是最小值。为了能让和(sum)最大,最先考虑的是a2n-2(因为a2n-1是最大值,没有数能与它构成一对,使它加到sum中),为了让a2n-2加到sum中,则需要让它和a2n-1组成一对;下一个考虑的就是a2n-4,同理为了让a2n-4加进来,就让它与a2n-3组成一对。因为每次加进来都是剩余数组中的最大值,所以最后的和(sum)也是最大的。

代码如下:

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

更多算法内容 关注  FunctionYcsdn博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值