#561
Array Partition
EasyArrayGreedySortingCounting SortGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
To maximize the sum of minimums, we can sort the array and pair adjacent elements. This works because pairing the smallest with the next smallest maximizes the contribution of each pair.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array in non-decreasing order.
- 2Step 2: Initialize a variable to hold the sum of minimums.
- 3Step 3: Iterate through the sorted array, adding every second element (the minimum of each pair) to the sum.
solution.py5 lines
1# Full working Python code
2
3def arrayPairSum(nums):
4 nums.sort()
5 return sum(nums[i] for i in range(0, len(nums), 2))ℹ
Complexity note: The sorting step dominates the time complexity, making it O(n log n), while we only use a constant amount of extra space.
- 1Sorting the array allows for optimal pairing of elements.
- 2Pairing adjacent sorted elements maximizes the contribution of each pair.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.