-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum Product Subarray
37 lines (33 loc) · 1.05 KB
/
Maximum Product Subarray
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// problem url: https://leetcode.com/problems/maximum-product-subarray/
// mode: Medium
// Maximum Product Subarray
class Solution {
public:
int maxProduct(vector<int>& nums) {
int size = nums.size();
int maxProductFromLeft = nums[0];
int maxProductFromRight = nums[size-1];
bool zeroPresent = false;
int tempProduct = 1;
for(int num: nums){
if(num == 0){
tempProduct = 1;
zeroPresent = true;
}else{
tempProduct *= num;
maxProductFromLeft = max(maxProductFromLeft, tempProduct);
}
}
tempProduct = 1;
for(int i=size-1; i>=0; i--){
if(nums[i]==0){
tempProduct = 1;
}else{
tempProduct *= nums[i];
maxProductFromRight = max(maxProductFromRight, tempProduct);
}
}
int ans = max(maxProductFromLeft, maxProductFromRight);
return zeroPresent ? max(ans, 0) : ans;
}
};