LeetCode Solution, Easy, 561. Array Partition I

陣列分割 I

561. Array Partition I

題目敘述

Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.

Example 1:

Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.

Example 2:

Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.

Constraints:

  • 1 <= n <= 10**4
  • nums.length == 2 * n
  • -10**4 <= nums[i] <= 10**4

Hint 1

Obviously, brute force won't help here. Think of something else, take some examples like 1,2,3,4.

Hint 2

How will you make pairs to get the result? There must be some pattern.

Hint 3

Did you observe that- Minimum element gets added to the result in a sacrifice of a maximum element?

Hint 4

Still won't be able to find pairs? Sort the array and try to find the pattern.

題目翻譯

有一個參數 nums 是一個整數陣列,其中的元素有 2n 個。今天要拆分這個陣列,元素兩兩一對。在這樣的分配之下,有許多種組合。要找出各種組合中,兩兩配對後其中的最小值的總是最大的。

解法解析

此題的解題邏輯是,要是配對中的最小值。那其實就從小到大排序後,取索引是 2n 的值即可。

解法範例

Go

func arrayPairSum(nums []int) int {
    sort.Ints(nums)

    sum := 0
    for i := 0; i < len(nums); i += 2 {
        sum += nums[i]
    }
    return sum
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var arrayPairSum = function (nums) {
    return nums.sort((a, b) => a - b).reduce((sum, cur, i) => (i % 2 === 0 ? (sum += cur) : sum), 0);
};

Kotlin

class Solution {
    fun arrayPairSum(nums: IntArray): Int {
        nums.sort()
        return nums.filterIndexed { index, _ -> index % 2 == 0 }.sum()
    }
}

PHP

class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function arrayPairSum($nums)
    {
        sort($nums);
        $sum = 0;
        for ($i = 0; $i < count($nums); $i += 2) {
            $sum += $nums[$i];
        }
        return $sum;
    }
}

Python

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        return sum(sorted(nums)[::2])

Rust

impl Solution {
    pub fn array_pair_sum(nums: Vec<i32>) -> i32 {
        let mut nums = nums;
        nums.sort();
        nums.iter().step_by(2).sum()
    }
}

Swift

class Solution {
    func arrayPairSum(_ nums: [Int]) -> Int {
        let nums: [Int] = nums.sorted()
        var res: Int = 0
        for i: Int in 0..<nums.count / 2 {
            res += nums[i * 2]
        }
        return res
    }
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!