Skip to content

Commit 68c77ff

Browse files
committed
Add solution and test-cases for problem 561
1 parent a337ff8 commit 68c77ff

File tree

3 files changed

+46
-9
lines changed

3 files changed

+46
-9
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# [561.Array Partition][title]
2+
3+
## Description
4+
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.
5+
6+
**Example 1:**
7+
8+
```
9+
Input: nums = [1,4,3,2]
10+
Output: 4
11+
Explanation: All possible pairings (ignoring the ordering of elements) are:
12+
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
13+
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
14+
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
15+
So the maximum possible sum is 4.
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
Input: nums = [6,2,6,5,1,2]
22+
Output: 9
23+
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
24+
```
25+
26+
## 结语
27+
28+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]
29+
30+
[title]: https://leetcode.com/problems/array-partition
31+
[me]: https://github.com/kylesliu/awesome-golang-algorithm
Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
import "sort"
4+
5+
func Solution(nums []int) int {
6+
sort.Ints(nums)
7+
ans := 0
8+
for i := 0; i < len(nums); i += 2 {
9+
ans += min(nums[i], nums[i+1])
10+
}
11+
return ans
512
}

leetcode/501-600/0561.Array-Partition/Solution_test.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs []int
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", []int{1, 4, 3, 2}, 4},
17+
{"TestCase2", []int{6, 2, 6, 5, 1, 2}, 9},
1918
}
2019

2120
// 开始测试
@@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
3029
}
3130
}
3231

33-
// 压力测试
32+
// 压力测试
3433
func BenchmarkSolution(b *testing.B) {
3534
}
3635

37-
// 使用案列
36+
// 使用案列
3837
func ExampleSolution() {
3938
}

0 commit comments

Comments
 (0)