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.
  • 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].
  • Example:
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).
  • Analysis:
Target is sum(min(a1, b1), min(a2, b2), ... , min(an, bn)). 

The best order in given array is a1 < b1 < a2 < b2 < ... < an < bn.

As a result, we sort the input array firstly.

Then, add values at odd index of sorted array.
  • Code - Java:
class Solution {
    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length;
        int result = 0;
        for (int i = 0; i < len - 1; i += 2) {
            result += nums[i];
        }
        return result;
    }
}
  • Code - C++:
class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int result = 0;
        int size = nums.size();
        for (int i = 0; i < size - 1; i += 2) {
            result += nums[i];
        }
        return result;
    }
};
  • Code - Python:
class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        result = 0
        numsLen = len(nums)
        for i in range(0, numsLen - 1, 2):
            result += nums[i]
        return result
  • Code - C:
int cmp(const int *a, const int *b) {
    return *a - *b;
}

int arrayPairSum(int* nums, int numsSize) {
    qsort(nums, numsSize, sizeof(int), cmp);
    int result = 0;
    for (int i = 0; i < numsSize; i += 2) {
        result += nums[i];
    }
    return result;
}
  • Time Complexity: O(NlogN), N is length of the input array
  • Space Complexity: O(1)

results matching ""

    No results matching ""