使用PHP解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 = 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个元素,被划分为n对,每对有2个元素,然后统计每对元素中最小元素值之和
其实从另个侧面来讲,就是求奇数项之和,因此这道题目在Leetcode上被踩的较多

解题思路:
把数组先升序排列,然后划分为等段大小(size=2),然后求出二维数组的第一项,在最后求整个数组之和

示例:

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function arrayPairSum($nums) {
        sort($nums);
        
        $numsChunk = array_chunk($nums, 2);
        $numsFirstItem = array_column($numsChunk, 0);
        
        return array_sum($numsFirstItem);
    }
}

你可能感兴趣的:(使用PHP解561. Array Partition I)