LeetCode 561: Array Partition

Problem Description

Explanation:

To maximize the sum of the minimum of each pair, we should pair the smallest number with the next smallest number in order to maximize the sum. Sorting the array and then pairing adjacent elements will achieve this.

  1. Sort the input array.
  2. Pair adjacent elements.
  3. Sum up the minimum of each pair to get the maximum sum.

Time complexity: O(n log n)
Space complexity: O(1)

Solutions

class Solution {
    public int arrayPairSum(int[] nums) {
        Arrays.sort(nums);
        int sum = 0;
        for (int i = 0; i < nums.length; i += 2) {
            sum += nums[i];
        }
        return sum;
    }
}

Loading editor...