-
Notifications
You must be signed in to change notification settings - Fork 0
/
152_maxProductSubArray.cpp
56 lines (40 loc) · 1.02 KB
/
152_maxProductSubArray.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
#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
int maxProduct(vector<int>& nums) {
int size = nums.size();
if (0 == size) {
return 0;
}
int crtMax = nums[0];
// for (int i = 0; i != size; ++i) {
// int max = 1;
// for (int j = i; j != size; ++j) {
// max *= nums[j];
// if (max > crtMax) {
// crtMax = max;
// }
// }
// }
int max = nums[0];
int min = nums[0];
for (int i = 1; i != size; ++i) {
int x = max;
int y = min;
max = std::max(nums[i], std::max(x * nums[i], y * nums[i]));
min = std::min(nums[i], std::min(y * nums[i], x * nums[i]));
if (crtMax < max) {
crtMax = max;
}
cout << max << " " << min << endl;
}
return crtMax;
}
int main(int argc, char const *argv[])
{
vector<int> vec = {2, 3, -2, 4};
auto ret = maxProduct(vec);
cout << "result = " << ret << endl;
return 0;
}