Welcome to Subscribe On Youtube

Question

Formatted question description: https://leetcode.ca/all/561.html

 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:
 n is a positive integer, which is in the range of [1, 10000].
 All the integers in the array will be in the range of [-10000, 10000].

Algorithm

Since we want to maximize the sum of the smaller values in each pair, then the two numbers in each pair must be as close as possible, because if the difference is too large and we only take the smaller number, then the big number will be wasted Lost.

Understand this, we only need to sort the array, and then every two in the order is a pair, we take out the first number in each pair and add up the smaller value.

Code

  • 
        class Solution {
            public int arrayPairSum(int[] nums) {
                //sort the array
                Arrays.sort(nums);
                int sum = 0;
                for(int i = 0; i < nums.length; i += 2) {
                    sum += nums[i];
                }
                return sum;
            }
        }
    
    
  • class Solution:
        def arrayPairSum(self, nums: List[int]) -> int:
            return sum(sorted(nums)[::2])
    
    ############
    
    class Solution(object):
      def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum([c for i, c in enumerate(sorted(nums)) if i % 2 == 0])
    
    
  • class Solution {
    public:
        int arrayPairSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            int ans = 0;
            for (int i = 0; i < nums.size(); i += 2) ans += nums[i];
            return ans;
        }
    };
    
  • func arrayPairSum(nums []int) int {
    	sort.Ints(nums)
    	ans := 0
    	for i := 0; i < len(nums); i += 2 {
    		ans += nums[i]
    	}
    	return ans
    }
    
  • /**
     * @param {number[]} nums
     * @return {number}
     */
    var arrayPairSum = function (nums) {
        nums.sort((a, b) => a - b);
        let ans = 0;
        for (let i = 0; i < nums.length; i += 2) {
            ans += nums[i];
        }
        return ans;
    };
    
    
  • impl Solution {
        pub fn array_pair_sum(mut nums: Vec<i32>) -> i32 {
            nums.sort();
            let n = nums.len();
            let mut i = 0;
            let mut res = 0;
            while i < n {
                res += nums[i];
                i += 2;
            }
            res
        }
    }
    
    

All Problems

All Solutions