LeetCode Js-561. Array Partition

    LeetCode Js-Array

    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.

    給予一個「二的倍數」的整數陣列叫 nums,將這些整數兩兩一組(a1, b1), (a2, b2), ..., (an, bn),
    並找出每組中的最小值,得到與回傳最大化的最小值總和。
    

    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.

    solution:
    1. 宣告 sum 為 0,以便後續加總。
    2. 運用 sort((a, b) => a – b)進行陣列的升冪排序。
    3. 運用 for 迴圈搭配 i += 2 的方式,抓取每兩個中的最小值進行加總。

    [1,2,3,4,5,6]
     0   2   4
    

    4. 回傳 sum。

    Code 1:

    var arrayPairSum = function(nums) {
        let sum = 0
        nums.sort((a, b) => a - b)
        for (let i = 0; i < nums.length; i += 2) {
            sum += nums[i]
        }
        return sum;
    };
    

    FlowChart:
    Example 1

    Input: nums = [1,4,3,2]
    
    sum = 0
    nums.sort => [1,2,3,4]
                  0   2  
    return sum //1 + 3 = 4
    

    Example 2

    Input: nums = [6,2,6,5,1,2]
    
    sum = 0
    nums.sort => [1,2,2,5,6,6]
                  0   2   4
    return sum //1 + 2 + 6 = 9
    

    Array.prototype.sort() : array.sort((a, b) => a - b)

    const months = ['March', 'Jan', 'Feb', 'Dec'];
    months.sort();
    console.log(months);
    // Expected output: Array ["Dec", "Feb", "Jan", "March"]
    
    const array1 = [1, 30, 4, 21, 100000];
    array1.sort();
    console.log(array1);
    // Expected output: Array [1, 100000, 21, 30, 4]
    
    var numbers = [4, 2, 5, 1, 3];
    numbers.sort(function(a, b) {
      return a - b;
    });
    console.log(numbers);
    
    // [1, 2, 3, 4, 5]