-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathmaximum-product-subarray.cpp
More file actions
77 lines (69 loc) · 2.04 KB
/
maximum-product-subarray.cpp
File metadata and controls
77 lines (69 loc) · 2.04 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
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
69
70
71
72
73
74
75
76
77
class Solution {
public:
int maxProduct(vector<int>& nums) {
long long ans = -1e15;
for(auto i : nums)ans=max(ans,(long long)i);
vector<long long>dp;
long long cur = 1;
vector<int>neg;
int n = nums.size();
for(int i=0;i<n;i++){
if(nums[i]==0){
if(dp.size()==0)continue;
ans=max(ans,cur);
if(cur>0){
dp.clear();
cur=1;
neg.clear();
continue;
}
if(dp.size()==1){
dp.clear();
cur=1;
neg.clear();
continue;
}
int idx = neg.back();
idx--;
if(idx>=0)ans=max(ans,dp[idx]);
idx = neg[0];
long long X = dp.back()/dp[idx];
ans=max(ans,X);
dp.clear();
cur=1;
neg.clear();
}else{
cur*=nums[i];
dp.push_back(cur);
if(nums[i]<0){
neg.push_back((int)dp.size()-1);
}
}
}
if(dp.size()){
ans=max(ans,cur);
if(cur>0){
dp.clear();
cur=1;
neg.clear();
}
else if(dp.size()==1){
dp.clear();
cur=1;
neg.clear();
}
else{
int idx = neg.back();
idx--;
if(idx>=0)ans=max(ans,dp[idx]);
idx = neg[0];
long long X = dp.back()/dp[idx];
ans=max(ans,X);
dp.clear();
cur=1;
neg.clear();
}
}
return ans;
}
};