Skip to content

Commit 91caef9

Browse files
aQuaaQua
aQua
authored and
aQua
committed
628 finish
1 parent cc36b15 commit 91caef9

File tree

2 files changed

+34
-14
lines changed

2 files changed

+34
-14
lines changed
Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,37 @@
11
package Problem0628
22

3-
import (
4-
"sort"
5-
)
6-
73
func maximumProduct(nums []int) int {
8-
sort.Ints(nums)
9-
l := len(nums)
10-
temp := append(nums[l-3:], nums[:3]...)
114

12-
max := nums[0] * nums[1] * nums[2]
5+
max := -1001
6+
max1 := -1001
7+
max2 := -1001
8+
min1 := 1001
9+
min2 := 1001
10+
11+
for _, n := range nums {
12+
switch {
13+
case n > max:
14+
max2, max1, max = max1, max, n
15+
case n > max1:
16+
max2, max1 = max1, n
17+
case n > max2:
18+
max2 = n
19+
}
1320

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
21+
switch {
22+
case n < min1:
23+
min2, min1 = min1, n
24+
case n < min2:
25+
min2 = n
1826
}
1927
}
2028

21-
return max
29+
return bigger(max1*max2, min1*min2) * max
30+
}
31+
32+
func bigger(a, b int) int {
33+
if a > b {
34+
return a
35+
}
36+
return b
2237
}

Algorithms/0628.maximum-product-of-three-numbers/maximum-product-of-three-numbers_test.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,19 @@ func Test_Problem0628(t *testing.T) {
2929

3030
qs := []question{
3131
question{
32-
para{[]int{-4, -3, -2, -1, 60}},
32+
para{[]int{-4, -3, -2, -1, 1, 1, 1, 1, 1, 60}},
3333
ans{720},
3434
},
35+
3536
question{
3637
para{[]int{1, 2, 3, 4}},
3738
ans{24},
3839
},
3940

41+
question{
42+
para{[]int{1, 2, 3}},
43+
ans{6},
44+
},
4045
// 如需多个测试,可以复制上方元素。
4146
}
4247

0 commit comments

Comments
 (0)