Skip to content

Commit 8b1ce9a

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 152_Maximum_Product_Subarray.java
1 parent 063f23a commit 8b1ce9a

File tree

1 file changed

+25
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)