[leetcode] 561. Array splitting I

Time:2021-7-12

Given an array of 2n in length, your task is to divide these numbers into n pairs, such as (A1, B1), (A2, B2),…, (an, BN), so as to maximize the sum of min (AI, BI) from 1 to n.

Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is equal to 2, and the maximum sum is 4 = min (1,2) + min (3,4)

Tips:

N is a positive integer in the range of [1,10000]
The range of elements in the array is [- 10000, 10000]
thinking

1. Array sorting
2. Get the number of groups
3. Loop the array and fill the contents into the array of slices for size comparison;
4. Add the small values

Solution code:
var arrayPairSum = function(nums) {
    /*Array sorting*/
    nums.sort((a, b) => a - b);
    /*Gets the number of groups*/
    let len = Math.ceil(nums.length / 2);
    let temp = 0;
    /*Loop the array and fill the contents into the sliced array for size comparison*/
    Array.from({
        length: len
    }, (v, w) => {
        temp += Math.min(...nums.slice(w * 2, w * 2 + 2));
    })
    return temp
};

[leetcode] 561. Array splitting I