zoukankan      html  css  js  c++  java
  • [LeetCode] 561. Array Partition I

    Easy

    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个整数的数组,将数组中的数字两两分组,求出这些组中的最小值相加之和的最大值。

    为使最后加和最大,那么就要各组选出的最小值尽可能大,当每一组的两个数字相差都最小时,得出的最小值之和才会最大。

    因此先对整个数组排序,然后从前往后依次两两组队,取出每组的最小值相加,就能得到最大的和。

    因为数组已经排过序了,所以就能省去取组内最小值这一步。当数组是非降序排列时,数组的偶数位就是各组的最小值。

    代码如下:

    class Solution {
    public:
        int arrayPairSum(vector<int>& nums) {
            int res=0;
            sort(nums.begin(),nums.end());
            for(int i=0;i<nums.size()/2;++i){
                res+=nums[i*2];
            }
            return res;
        }
    };
  • 相关阅读:
    【python cookbook学习笔记】给字典增加一个条目
    UI设计星级评价
    弱引用和循环引用
    lua数据类型
    lua虚拟机笔记
    c++对象模型笔记
    使树控件方向键无效
    实现CListCtrl自定义行高
    创建对话框时常用配置
    C++格式化输出总结
  • 原文地址:https://www.cnblogs.com/cff2121/p/11446739.html
Copyright © 2011-2022 走看看