We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Partition

Number: 561

Difficulty: Easy

Paid? No

Companies: Amazon, Yahoo, Apple


Problem Description

Given an integer array nums of 2n integers, group these integers into n pairs such that the sum of min(a, b) for each pair is maximized. Return the maximized sum.


Key Insights

  • Sorting the array puts numbers in ascending order, which enables pairing the smallest numbers together.
  • Pairing consecutive elements guarantees that each pair's minimum is as high as possible.
  • For integers in a fixed range, counting sort can be used for optimal performance.

Space and Time Complexity

Time Complexity: O(n log n) due to sorting (O(n) if using counting sort on a fixed range).
Space Complexity: O(1) or O(n) depending on the sorting algorithm used.


Solution

The solution works by first sorting the nums array. Once sorted, pairing each element at even indices with its immediate neighbor ensures that the smaller element of each pair is as large as possible given the constraints. This approach maximizes the overall sum of the minimums from each pair. The main trick is to recognize that, after sorting, the optimal pairing is simply consecutive elements.


Code Solutions

def arrayPairSum(nums):
    # Sort the array in ascending order
    nums.sort()
    result = 0
    # Iterate over the sorted list, adding the element at every even index (first element of each pair)
    for i in range(0, len(nums), 2):
        result += nums[i]
    return result

# Example test
print(arrayPairSum([1, 4, 3, 2]))  # Expected output: 4
← Back to All Questions