LeetCode – 561. Array Partition I

題目來源: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:

Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 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的整數陣列並分成n組,接著從每組中取出較小的數字相加為sum,並讓sum盡可能的大。

其中題目有兩條規定

  1. n只會是正整數,且範圍只會在[1, 10000]之間
  2. 陣列中的整數範圍介在[-10000, 10000]之間

解法:

題目不難,最簡單又直覺的做法是直接將Input的array做排序

由於排序完後每組較小的值都在左邊,因此將array中為偶數的index相加即是答案

 

 


網站:http://wp.mlab.tw/
GitHub:https://github.com/yoll522/LeetCode
程式碼:https://github.com/yoll522/LeetCode/tree/master/561.%20Array%20Partition%20I

 

Leave a Reply

你的電子郵件位址並不會被公開。 必要欄位標記為 *