> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Array Partition Python Solution with Tests

> Tested Python solution for LeetCode 561 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 561, [Easy](/catalog/easy). Topics: [Array](/catalog/topics/array), [Greedy](/catalog/topics/greedy), [Sorting](/catalog/topics/sorting), Counting Sort. [View on LeetCode](https://leetcode.com/problems/array-partition/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 561   # by problem number
lcpy gen -s array_partition   # by problem name
```

## Problem

Given an integer array `nums` of `2n` integers, group these integers into `n` pairs (a\<sub>1\</sub>, b\<sub>1\</sub>), (a\<sub>2\</sub>, b\<sub>2\</sub>), ..., (a\<sub>n\</sub>, b\<sub>n\</sub>) such that the sum of `min(a<sub>i</sub>, b<sub>i</sub>)` for all `i` is **maximized**. Return *the maximized sum*.

### Examples

```
Input: nums = [1,4,3,2]
Output: 4
```

**Explanation:** All possible pairings (ignoring the ordering of elements) are:

1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
   So the maximum possible sum is 4.

```
Input: nums = [6,2,6,5,1,2]
Output: 9
```

**Explanation:** The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.

### Constraints

* `1 <= n <= 10^4`
* `nums.length == 2 * n`
* `-10^4 <= nums[i] <= 10^4`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/array_partition/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/array_partition/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log n)
    # Space: O(n) for the sort
    def array_pair_sum(self, nums: list[int]) -> int:
        nums.sort()
        return sum(nums[::2])
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) for the sort |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.