Skip to content

Commit ce5152f

Browse files
committed
Maximum Product Subarray
1 parent 790350b commit ce5152f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// TC: O(n)
2+
// SC: O(1)
3+
class Solution {
4+
public int maxProduct(int[] nums) {
5+
int currentMax = nums[0];
6+
int currentMin = nums[0];
7+
int maxProduct = nums[0];
8+
9+
for (int i = 1; i < nums.length; i++) {
10+
if (nums[i] < 0) {
11+
int temp = currentMax;
12+
currentMax = currentMin;
13+
currentMin = temp;
14+
}
15+
16+
currentMax = Math.max(nums[i], currentMax * nums[i]);
17+
currentMin = Math.min(nums[i], currentMin * nums[i]);
18+
19+
maxProduct = Math.max(maxProduct, currentMax);
20+
}
21+
22+
return maxProduct;
23+
}
24+
}

0 commit comments

Comments
 (0)