Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions leetcode/501-600/0561.Array-Partition/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# [561.Array Partition][title]

## Description
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 1:**

```
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.
```

**Example 2:**

```
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.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/array-partition
[me]: https://github.com/kylesliu/awesome-golang-algorithm
11 changes: 9 additions & 2 deletions leetcode/501-600/0561.Array-Partition/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package Solution

func Solution(x bool) bool {
return x
import "sort"

func Solution(nums []int) int {
sort.Ints(nums)
ans := 0
for i := 0; i < len(nums); i += 2 {
ans += min(nums[i], nums[i+1])
}
return ans
}
13 changes: 6 additions & 7 deletions leetcode/501-600/0561.Array-Partition/Solution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{1, 4, 3, 2}, 4},
{"TestCase2", []int{6, 2, 6, 5, 1, 2}, 9},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading