Leetcode 561. Array Partition I

Given an array of2nintegers, your task is to group these integers intonpairs 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.

Note:

nis a positive integer, which is in the range of [1, 10000].

All the integers in the array will be in the range of [-10000, 10000].

给出一个长度为 2n 的整数数组,你的任务是将这些整数分成n组,每组两个一对,并求得所有分组中较小的数的总和(这个总和的值要尽可能的大)

思路:将整个数组升序排列,从下标为 0 处开始,每隔两个 取一个,并求和

return sum(sorted(nums)[::2])  #sum求和 sorted升序排列 [::2] 步长为2取

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • 原题是: Given an array of 2n integers, your task is to group...
    小双2510阅读 1,423评论 0 0
  • 还是米饭,接着炒吧,今天做了个小造型,恰好有葡萄,于是装点了一下。 稳锅那天的海参还剩了一个,干脆切成条熬个海参汤...
    小蓝菊阅读 1,027评论 0 0
  • 【读经】 诗篇118 【金句】 你们要称谢耶和华,因他本为善;他的慈爱永远长存!(诗篇 118:29 和合本) 【...
    chanor阅读 1,085评论 0 0
  • 2017年7月12日 昨晚梦到我生孩子了,我挺着不太大的肚子,很着急心切地跟蛋总说:“老公,我要生了,宫缩了……”...
    米渣小姐阅读 1,228评论 0 0