Array Partition I (数组分隔两两最小值中Sum最大值)

爱被打了一巴掌 2022-03-31 02:21 189阅读 0赞

LeetCode 561. 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:

  1. Input: [1,4,3,2]
  2. Output: 4
  3. 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].

题目标签:Array

  这道题目给了我们一个数组有2n integers, 需要我们把这个数组分成n对,然后从每一对里面拿小的那个数字,把所有的加起来,返回这个sum。并且要使这个sum 尽量最大。如何让sum 最大化呢,我们想一下,如果是两个数字,一个很小,一个很大,这样的话,取一个小的数字,就浪费了那个大的数字。所以我们要使每一对的两个数字尽可能接近。我们先把nums sort 一下,让它从小到大排列,接着每次把index: 0, 2, 4…偶数位的数字加起来就可以了。

  1. public class Solution
  2. {
  3. public int arrayPairSum(int[] nums)
  4. {
  5. int sum = 0;
  6. Arrays.sort(nums);
  7. for(int i=0; i<nums.length; i+=2)
  8. sum += nums[i];
  9. return sum;
  10. }
  11. }

发表评论

表情:
评论列表 (有 0 条评论,189人围观)

还没有评论,来说两句吧...

相关阅读