-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmaxProduct.go
More file actions
36 lines (31 loc) · 750 Bytes
/
Copy pathmaxProduct.go
File metadata and controls
36 lines (31 loc) · 750 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
/* https://leetcode.com/problems/maximum-product-subarray/description/
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
*/
package ldp
func maxProduct(nums []int) int {
if len(nums) == 0 {
return 0
}
max := func(a, b int) int {
if a > b {
return a
}
return b
}
min := func(a, b int) int {
if a < b {
return a
}
return b
}
maxMul, minMul, res := nums[0], nums[0], nums[0]
for i := 1; i < len(nums); i++ {
a, b := maxMul*nums[i], minMul*nums[i]
maxMul = max(max(a, b), nums[i])
minMul = min(min(a, b), nums[i])
res = max(res, maxMul)
}
return res
}