-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path152.cpp
More file actions
52 lines (47 loc) · 1.49 KB
/
152.cpp
File metadata and controls
52 lines (47 loc) · 1.49 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
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
int posProduct = nums[0];
int negProduct = nums[0];
int maxVal = nums[0];
for (int i = 1; i < n; i++) {
int nextPos, nextNeg;
nextPos = max({nums[i], posProduct * nums[i], negProduct * nums[i]});
nextNeg = min({nums[i], posProduct * nums[i], negProduct * nums[i]});
maxVal = max(maxVal, nextPos);
posProduct = nextPos;
negProduct = nextNeg;
}
return maxVal;
}
};
// v2
// class Solution {
// public:
// int maxProduct(vector<int>& nums) {
// int positive = 0;
// int negative = 0;
// int res = INT_MIN;
// for (auto& num : nums) {
// if (num == 0) {
// positive = 0;
// negative = 0;
// res = max(res, 0);
// }
// else if (num > 0) {
// positive = max(num, positive * num);
// negative = min(num, negative * num);
// res = max(res, positive);
// }
// else {
// int temp = positive;
// positive = max(0, negative * num);
// if (positive > 0) res = max(res, positive);
// negative = min(num, temp * num);
// res = max(res, negative);
// }
// }
// return res;
// }
// };