Skip to content

Commit cddf0cf

Browse files
committed
feat: maximum-product-subarray
1 parent 55ca2b8 commit cddf0cf

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)