-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximumProductSubarray.go
More file actions
56 lines (51 loc) · 955 Bytes
/
maximumProductSubarray.go
File metadata and controls
56 lines (51 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package leetcode
import (
"fmt"
"math"
)
func MaxProduct(nums []int) int {
return maxProduct(nums)
}
func maxProduct(nums []int) int {
r, imax, imin := nums[0], nums[0], nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] < 0 {
imax, imin = imin, imax
}
if nums[i] < imax*nums[i] {
imax = imax * nums[i]
} else {
imax = nums[i]
}
if nums[i] < imin*nums[i] {
imin = nums[i]
} else {
imin = imin * nums[i]
}
if r < imax {
r = imax
}
fmt.Println("min, max", imin, imax)
}
return r
}
func maxProductBF(nums []int) int {
maxValue := math.MinInt64
dp := make([]int, len(nums))
for start := 0; start < len(nums); start++ {
for end := start; end < len(nums); end++ {
if dp[end] != 0 {
dp[end] = dp[end] / nums[start-1]
} else {
dp[end] = 1
for i := start; i <= end; i++ {
dp[end] *= nums[i]
}
}
if dp[end] > maxValue {
maxValue = dp[end]
}
}
}
return maxValue
}