File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * <a href="https://leetcode.com/problems/maximum-product-subarray/">week9-3. maximum-product-subarray</a>
3
+ * <li>Description: Given an integer array nums, find a subarray that has the largest product, and return the product. </li>
4
+ * <li>Topics: Array, Dynamic Programming </li>
5
+ * <li>Time Complexity: O(N), Runtime 2ms </li>
6
+ * <li>Space Complexity: O(1), Memory 45.42MB </li>
7
+ */
8
+ class Solution {
9
+ public int maxProduct (int [] nums ) {
10
+ int maxSoFar = nums [0 ];
11
+ int minSoFar = nums [0 ];
12
+ int result = nums [0 ];
13
+
14
+ for (int i = 1 ; i < nums .length ; i ++) {
15
+ int cur = nums [i ];
16
+ int tempMax = maxSoFar ;
17
+
18
+ maxSoFar = Math .max (cur , Math .max (cur * maxSoFar , cur * minSoFar ));
19
+ minSoFar = Math .min (cur , Math .min (cur * tempMax , cur * minSoFar ));
20
+
21
+ result = Math .max (result , maxSoFar );
22
+ }
23
+
24
+ return result ;
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments