-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_maximum-product-subarray.cpp
68 lines (56 loc) · 1.32 KB
/
06_maximum-product-subarray.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// DATE: 28-July-2023
/* PROGRAM: 06_Array - Maximum Product SubArray
https://leetcode.com/problems/maximum-product-subarray/
*/
// @ankitsamaddar @July_2023
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProduct(vector<int> &nums) {
int res = INT_MIN;
int curMin = 1, curMax = 1, tmp = 0;
bool zeroPresent = false;
for (int n : nums) {
if (n == 0) {
curMin = 1;
curMax = 1;
zeroPresent = true;
continue;
}
tmp = curMax * n;
curMax = max({n * curMax, n * curMin, n});
curMin = min({tmp, n * curMin, n});
res = max(res, curMax);
}
if (zeroPresent)
return max(res, 0);
return res;
}
};
/* Solution 2 - fastest - using left and right product
class Solution {
public:
int maxProduct(vector<int>& nums) {
int right_p = 1, left_p = 1, maxProduct = INT_MIN;
for(int i = 0;i<nums.size();i++){
if(left_p==0) left_p=1;
if(right_p==0) right_p=1;
left_p *= nums[i];
right_p *= nums[nums.size()-i-1];
maxProduct = max({left_p,right_p,maxProduct});
}
return maxProduct;
}
};
*/
int main() {
int nums[] = {-2, 0, -1};
vector<int> v(nums, nums + sizeof(nums) / sizeof(int));
Solution sol;
int result = sol.maxProduct(v);
cout << result << endl;
return 0;
}