Array Partition — LeetCode 561 Python Solution
- Problem
- #561
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
Example
- Input
- nums = [1,4,3,2]
- Output
- 4
- Explanation
- All possible pairings (ignoring the ordering of elements) are:
Python solution
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[::2])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 561. Array Partition is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 561. Array Partition?
- LeetCode 561. Array Partition is rated Easy on LeetCode.
- What is the time complexity of LeetCode 561. Array Partition?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 561. Array Partition?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 561. Array Partition cover?
- LeetCode 561. Array Partition is tagged Greedy, Array, Counting Sort and Sorting on LeetCode.