-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_Product_Subarray.cpp
More file actions
41 lines (40 loc) · 1.04 KB
/
Maximum_Product_Subarray.cpp
File metadata and controls
41 lines (40 loc) · 1.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
# number : 152
class Solution {
public:
int maxProduct(vector<int>& nums) {
int result = INT_MIN;
int length = (int)nums.size();
if (length <= 0)
return 0;
int *dpMax = new int[length];
int *dpMin = new int[length];
dpMax[0] = nums[0];
dpMin[0] = nums[0];
for (int i = 1; i < length; i++)
{
int maxP = dpMax[i-1] * nums[i];
int minP = dpMin[i-1] * nums[i];
int maxNum = Max(maxP, minP, nums[i]);
int minNum = Min(maxP, minP, nums[i]);
dpMax[i] = maxNum;
dpMin[i] = minNum;
if (maxNum > result)
result = maxNum;
}
return result > dpMax[0] ? result : dpMax[0];
}
int Max(int a, int b, int c)
{
if (a > b)
return a > c ? a : c;
else
return b > c ? b : c;
}
int Min(int a, int b, int c)
{
if (a < b)
return a < c ? a : c;
else
return b < c ? b : c;
}
};