Skip to content

Commit cc36b15

Browse files
aQuaaQua
aQua
authored and
aQua
committed
628 accepted
1 parent 3bd369c commit cc36b15

File tree

3 files changed

+47
-8
lines changed

3 files changed

+47
-8
lines changed

Algorithms/0628.maximum-product-of-three-numbers/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,23 @@
11
# [628. Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/)
22

33
## 题目
4+
Given an integer array, find three numbers whose product is maximum and output the maximum product.
45

6+
Example 1:
7+
```
8+
Input: [1,2,3]
9+
Output: 6
10+
```
11+
Example 2:
12+
```
13+
Input: [1,2,3,4]
14+
Output: 24
15+
```
16+
Note:
17+
18+
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
19+
20+
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
521

622
## 解题思路
723

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

3+
import (
4+
"sort"
5+
)
6+
7+
func maximumProduct(nums []int) int {
8+
sort.Ints(nums)
9+
l := len(nums)
10+
temp := append(nums[l-3:], nums[:3]...)
11+
12+
max := nums[0] * nums[1] * nums[2]
13+
14+
for i := 0; i < len(temp)-3; i++ {
15+
t := temp[i] * temp[i+1] * temp[i+2]
16+
if max < t {
17+
max = t
18+
}
19+
}
20+
21+
return max
22+
}
Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0628
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,32 +15,35 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
one []int
1919
}
2020

2121
// ans 是答案
2222
// one 代表第一个答案
2323
type ans struct {
24-
one string
24+
one int
2525
}
2626

2727
func Test_Problem0628(t *testing.T) {
2828
ast := assert.New(t)
2929

3030
qs := []question{
31-
3231
question{
33-
para{""},
34-
ans{""},
32+
para{[]int{-4, -3, -2, -1, 60}},
33+
ans{720},
3534
},
36-
35+
question{
36+
para{[]int{1, 2, 3, 4}},
37+
ans{24},
38+
},
39+
3740
// 如需多个测试,可以复制上方元素。
3841
}
3942

4043
for _, q := range qs {
4144
a, p := q.ans, q.para
4245
fmt.Printf("~~%v~~\n", p)
4346

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
47+
ast.Equal(a.one, maximumProduct(p.one), "输入:%v", p)
4548
}
4649
}

0 commit comments

Comments
 (0)