LeetCode 561: Array Partition Solution

Master LeetCode problem 561 (Array Partition), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

561. Array Partition

Problem Explanation

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)

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 561 (Array Partition)?

This page provides optimized solutions for LeetCode problem 561 (Array Partition) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 561 (Array Partition)?

The time complexity for LeetCode 561 (Array Partition) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 561 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 561 in Java, C++, or Python.

Back to LeetCode Solutions