561. Array Partition I

1. Description

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.

2. Example

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.

3. Constraints

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

4. Solutions

My Accepted Solution

n = m_nums.size()
Time complexity: O($nlog_2n$)
Space complexity: O(1)

class Solution 
{
public:
    // int arrayPairSum(vector<int>& nums)
    int arrayPairSum(vector<int> &m_nums) 
    {
        sort(m_nums.begin(), m_nums.end());
        
        int result = 0;
        for(int i = 0; i < m_nums.size(); i += 2)
            result += m_nums[i];
        
        return result;
    }
};

4.1 Bucket Sort

n = m_nums.size()
Time complexity: O(n)
Space complexity: O(n)

// the range of number is [-10000, 10000], it is pretty small, so we could use bucket sort

class Solution 
{
public:
    // int arrayPairSum(vector<int>& nums)
    int arrayPairSum(vector<int> &i_nums) 
    {
        vector<int> buckets(20001); // the range is [-10000, 10000]
        for(auto num : i_nums)
            buckets[num + 10000]++;
        
        int result = 0;
        for(int i = 0; i < buckets.size(); )
        {
            while(i < buckets.size() && buckets[i] == 0) i++;
            
            // there must be even numbers
            // so we just need to judge whether we have the first number in pairs
            if(i == buckets.size()) break;
            
            buckets[i]--;
            result += (i - 10000);
            
            while(i < buckets.size() && buckets[i] == 0) i++;
            
            buckets[i]--;
        }
        
        return result;
    }
};
Last updated:
Tags: Array
comments powered by Disqus