Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 3206c5f

Browse files
aQuaaQua
aQua
authored and
aQua
committed
152 finish
1 parent 3d06b66 commit 3206c5f

File tree

1 file changed

+16
-30
lines changed

1 file changed

+16
-30
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,27 @@
11
package Problem0152
22

33
func maxProduct(a []int) int {
4-
Len := len(a)
4+
cur, neg, max := 1, 1, a[0]
55

6-
// maxs 用来存放最大值
7-
maxs := make([]int, Len)
8-
maxs[0] = a[0]
9-
// mins 用来存放最小值
10-
mins := make([]int, Len)
11-
mins[0] = a[0]
6+
for i := 0; i < len(a); i++ {
127

13-
for i := 1; i < Len; i++ {
14-
if a[i] > 0 {
15-
maxs[i] = a[i] * maxs[i-1]
16-
// 因为有可能 masx[i-1] <= 0
17-
// 所以,需要这个步骤更新答案
18-
if a[i] > a[i]*maxs[i-1] {
19-
maxs[i] = a[i]
20-
}
21-
mins[i] = a[i] * mins[i-1]
22-
} else if a[i] < 0 {
23-
maxs[i] = a[i] * mins[i-1]
24-
mins[i] = a[i] * maxs[i-1]
25-
// 因为有可能 maxs[i-1] <= 0
26-
// 所以,需要这个步骤更新答案
27-
if a[i] < a[i]*maxs[i-1] {
28-
mins[i] = a[i]
29-
}
8+
switch {
9+
case a[i] > 0:
10+
cur, neg = a[i]*cur, a[i]*neg
11+
case a[i] < 0:
12+
cur, neg = a[i]*neg, a[i]*cur
13+
default:
14+
cur, neg = 0, 1
15+
}
16+
17+
if max < cur {
18+
max = cur
3019
}
31-
}
3220

33-
res := maxs[0]
34-
for _, m := range maxs {
35-
if res < m {
36-
res = m
21+
if cur <= 0 {
22+
cur = 1
3723
}
3824
}
3925

40-
return res
26+
return max
4127
}

0 commit comments

Comments
 (0)