File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
152.Maximum Product Subarray Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
2
+
3
+ ** Example 1:**
4
+ ```
5
+ Input: [2,3,-2,4]
6
+ Output: 6
7
+ Explanation: [2,3] has the largest product 6.
8
+ ```
9
+ ** Example 2:**
10
+ ```
11
+ Input: [-2,0,-1]
12
+ Output: 0
13
+ Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
14
+ ```
15
+
16
+ ** Solution:**
17
+
18
+ ``` golang
19
+ func maxProduct (nums []int ) int {
20
+ n := len (nums)
21
+ if n == 1 {
22
+ return nums[0 ]
23
+ }
24
+
25
+ dp := make ([][2 ]int , n)
26
+ if nums[0 ] < 0 {
27
+ dp[0 ][1 ] = nums[0 ]
28
+ } else {
29
+ dp[0 ][0 ] = nums[0 ]
30
+ }
31
+
32
+ var ans int = dp[0 ][0 ]
33
+ for i := 1 ; i < n; i++ {
34
+ if nums[i] > 0 {
35
+ dp[i][0 ] = max (dp[i-1 ][0 ] * nums[i], nums[i])
36
+ dp[i][1 ] = min (dp[i-1 ][1 ] * nums[i], nums[i])
37
+ } else {
38
+ dp[i][1 ] = min (dp[i-1 ][0 ] * nums[i], nums[i])
39
+ dp[i][0 ] = max (dp[i-1 ][1 ] * nums[i], nums[i])
40
+ }
41
+ ans = max (ans, dp[i][0 ])
42
+ }
43
+
44
+ return ans
45
+ }
46
+
47
+ func max (a , b int ) int {
48
+ if a > b {
49
+ return a
50
+ }
51
+ return b
52
+ }
53
+
54
+ func min (a , b int ) int {
55
+ if a < b {
56
+ return a
57
+ }
58
+ return b
59
+ }
60
+ ```
You can’t perform that action at this time.
0 commit comments