-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0152. Maximum Product Subarray.cpp
More file actions
40 lines (37 loc) · 1.12 KB
/
0152. Maximum Product Subarray.cpp
File metadata and controls
40 lines (37 loc) · 1.12 KB
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
class Solution {
public:
// helper to get max
int getMax(int a, int b, int c) {
if (a >= b && a >= c)
return a;
if (b >= a && b >= c)
return b;
return c;
}
// helper to get min
int getMin(int a, int b, int c) {
if (a <= b && a <= c)
return a;
if (b <= a && b <= c)
return b;
return c;
}
int maxProduct(vector<int> &nums) {
// init -- prev and curr for simultaneous update
int prevMin, prevMax, currMin, currMax, ans;
prevMin = prevMax = currMin = currMax = ans = nums[0];
// modified Kadane's
for (int i = 1; i < nums.size(); i++) {
// keep track of max and min --> for both pos and neg prod
currMin = getMin(prevMax * nums[i], prevMin * nums[i], nums[i]);
currMax = getMax(prevMax * nums[i], prevMin * nums[i], nums[i]);
// update ans
if (currMax > ans)
ans = currMax;
// update previous
prevMin = currMin;
prevMax = currMax;
}
return ans;
}
};