Skip to content

Commit 487934b

Browse files
committed
Add solution and test-cases for problem 1262
1 parent a01e89c commit 487934b

File tree

3 files changed

+40
-22
lines changed

3 files changed

+40
-22
lines changed

leetcode/1201-1300/1262.Greatest-Sum-Divisible-by-Three/README.md

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,31 @@
11
# [1262.Greatest Sum Divisible by Three][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
Given an integer array `nums`, return the **maximum possible sum** of elements of the array such that it is divisible by three.
75

86
**Example 1:**
97

108
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
9+
Input: nums = [3,6,5,1,8]
10+
Output: 18
11+
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
1312
```
1413

15-
## 题意
16-
> ...
17-
18-
## 题解
14+
**Example 2:**
1915

20-
### 思路1
21-
> ...
22-
Greatest Sum Divisible by Three
23-
```go
16+
```
17+
Input: nums = [4]
18+
Output: 0
19+
Explanation: Since 4 is not divisible by 3, do not pick any number.
2420
```
2521

22+
**Example 3:**
23+
24+
```
25+
Input: nums = [1,2,3,4,4]
26+
Output: 12
27+
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
28+
```
2629

2730
## 结语
2831

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(nums []int) int {
4+
dp := []int{-1, -1, -1}
5+
dp[0] = 0
6+
7+
for _, num := range nums {
8+
t := make([]int, 3)
9+
copy(t, dp)
10+
for _, i := range t {
11+
if i >= 0 {
12+
newR := (i + num) % 3
13+
if i+num > dp[newR] {
14+
dp[newR] = i + num
15+
}
16+
}
17+
}
18+
}
19+
return dp[0]
520
}

leetcode/1201-1300/1262.Greatest-Sum-Divisible-by-Three/Solution_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ 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{3, 6, 5, 1, 8}, 18},
17+
{"TestCase2", []int{4}, 0},
18+
{"TestCase3", []int{1, 2, 3, 4, 4}, 12},
1919
}
2020

2121
// 开始测试
@@ -30,10 +30,10 @@ func TestSolution(t *testing.T) {
3030
}
3131
}
3232

33-
// 压力测试
33+
// 压力测试
3434
func BenchmarkSolution(b *testing.B) {
3535
}
3636

37-
// 使用案列
37+
// 使用案列
3838
func ExampleSolution() {
3939
}

0 commit comments

Comments
 (0)