[leetcode]561. Array Partition I

来源:互联网 发布:cba数据 编辑:程序博客网 时间:2024/05/29 17:17

题目链接

问题描述:

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 个整数的数组,任务是将其以 2 个为一组进行分组,分成 n 组,(a1, b1), (a2, b2), … ,(an, bn), 并使得

i=1nmin(ai,bi)
为最大值.


思路
首先对于给定的 n,总和 St 是确定的,即
St = (a1 + b1) + (a2 + b2) + … + (an + bn)
题目要求的最大的和为
Sm = a1 + a2 + … + an
其中有
Sd = (b1 - a1) + (b2 - a1) + … + (bn - an)
可得
Sm = (St - Sd) / 2
则当 Sd 为最小时,Sm有最大值
当 a1, b1, …, an, bn 按大小排列组合时,Sd 有最小值


代码实现

public class Solution {    public int arrayPairSum(int[] nums) {        Arrays.sort(nums);        int length = nums.length / 2 - 1;        int sum = 0;        while (length >= 0) {            sum += nums[2 * length--];        }        return sum;    }}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机为什么总显示内存不足怎么办 小米云服务满了怎么办 魅蓝s6声音小怎么办 华为畅享7s丢失怎么办 华为耳机孔坏了怎么办 苹果手机耳机插孔坏了怎么办 荣耀8听筒声音小怎么办 荣耀8听筒音量小怎么办 华为荣耀6声音小怎么办 华为荣耀v8通话声音小怎么办 华为p20没有耳机孔怎么办 华为荣耀手机耳机声音小怎么办 小米5x显示耳机怎么办 手机进水听音乐人声小怎么办 华为荣耀v8手机音量小怎么办 手机充电孔松了怎么办 华为荣耀7卡顿怎么办 华为手机话筒没声音怎么办 苹果x耳机进水了怎么办 苹果6p进水了怎么办 华为手机声音变耳机模式怎么办 手机设置成耳机模式怎么办 opop耳机一个没有声音怎么办 oppo手机上显示耳机模式怎么办 微信显示耳机模式怎么办 微信变成耳机模式怎么办 5s变成耳机模式怎么办 华为手机一直是耳机模式怎么办 华为手机进水了耳机模式怎么办 蓝牙耳机通话声音小怎么办 华为手机自动进入耳机模式怎么办 华为手机耳机怎么挂了电话怎么办 华为手机听筒声音小怎么办 华为p9手机听筒声音小怎么办 苹果6总是耳机模式怎么办 苹果没有插耳机模式怎么办 苹果手机切换耳机模式怎么办 苹果6s出现耳机模式怎么办 苹果6变成了耳机模式怎么办 苹果手机成耳机模式了怎么办 华为mate8耳机声音小怎么办