博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 561. Array Partition I_Easy tag: Sort
阅读量:5298 次
发布时间:2019-06-14

本文共 1708 字,大约阅读时间需要 5 分钟。

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

 

思路参考, 

In order to understand this approach, let us look at the problem from a different perspective. We need to form the pairings of the array's elements such that the overall sum of the minimum out of such pairings is maximum. Thus, we can look at the operation of choosing the minimum out of the pairing, say (a, b)(a,b) as incurring a loss of a - bab(if a> ba>b), in the maximum sum possible.

The total sum will now be maximum if the overall loss incurred from such pairings is minimized. This minimization of loss in every pairing is possible only if the numbers chosen for the pairings lie closer to each other than to the other elements of the array.

Taking this into consideration, we can sort the elements of the given array and form the pairings of the elements directly in the sorted order. This will lead to the pairings of elements with minimum difference between them leading to the maximization of the required sum.

T: O(nlgn)    S; O(1)

 

Code

class Solution:    def arrayPairSum(self, nums):        """        :type nums: List[int]        :rtype: int        """        nums.sort()        ans = 0        for i in range(0, len(nums), 2):            ans += nums[i]        return ans

 

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9458374.html

你可能感兴趣的文章
Node.js 入门:Express + Mongoose 基础使用
查看>>
plsql使用,为什么可以能看见其他用户的表
查看>>
一步步教你轻松学奇异值分解SVD降维算法
查看>>
使用pager进行分页
查看>>
UVA - 1592 Database
查看>>
Fine Uploader文件上传组件
查看>>
javascript中的传递参数
查看>>
objective-c overview(二)
查看>>
python查询mangodb
查看>>
consonant combination
查看>>
驱动的本质
查看>>
Swift的高级分享 - Swift中的逻辑控制器
查看>>
Swagger简单介绍
查看>>
Python数据分析入门案例
查看>>
vue-devtools 获取到 vuex store 和 Vue 实例的?
查看>>
Linux 中【./】和【/】和【.】之间有什么区别?
查看>>
内存地址对齐
查看>>
看门狗 (监控芯片)
查看>>
#ifndef #define #endif
查看>>
css背景样式
查看>>