Skip to content

Commit 682eb5f

Browse files
committed
maximum_product_subarray
1 parent d6d35bf commit 682eb5f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
135135
#### [149. Max Points on a Line](https://github.com/hitzzc/go-leetcode/tree/master/max_points_on_a_line)
136136
#### [150. evaluate reverse polish notation](https://github.com/hitzzc/go-leetcode/tree/master/evaluate_reverse_polish_notation)
137137
#### [151. reverse words in a string](https://github.com/hitzzc/go-leetcode/tree/master/reverse_words_in_a_string)
138+
#### [152. maximum product subarray](https://github.com/hitzzc/go-leetcode/tree/master/maximum_product_subarray)
138139

139140

140141

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package maximum_product_subarray
2+
3+
func maxProduct(nums []int) int {
4+
if len(nums) == 0 {
5+
return 0
6+
}
7+
if len(nums) == 1 {
8+
return nums[0]
9+
}
10+
ret, preMax, preMin := nums[0], nums[0], nums[0]
11+
var temp int
12+
for i := 1; i < len(nums); i++ {
13+
temp = preMax
14+
preMax = max(max(nums[i], nums[i]*preMax), nums[i]*preMin)
15+
preMin = min(min(nums[i], nums[i]*preMin), nums[i]*temp)
16+
ret = max(ret, preMax)
17+
}
18+
return ret
19+
}
20+
21+
func max(i, j int) int {
22+
if i > j {
23+
return i
24+
}
25+
return j
26+
}
27+
28+
func min(i, j int) int {
29+
if i < j {
30+
return i
31+
}
32+
return j
33+
}

0 commit comments

Comments
 (0)