LeetCode-Easy-Java——Array Partition I

来源:互联网 发布:淘宝一口价设置技巧 编辑:程序博客网 时间:2024/05/29 19:04

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: 4Explanation: 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博客

原创粉丝点击