-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_Product_Subarray.cpp
More file actions
76 lines (66 loc) · 1.39 KB
/
Maximum_Product_Subarray.cpp
File metadata and controls
76 lines (66 loc) · 1.39 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
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cassert>
using namespace std;
#define MAX(x,y) ((x)>(y)?(x):(y))
#define MIN(x,y) ((x)<(y)?(x):(y))
// 思路:用两个指针来指向字数组的头尾
int maxProduct(int A[], int n)
{
assert(n > 0);
int subArrayProduct = -32768;
for (int i = 0; i != n; ++ i) {
int nTempProduct = 1;
for (int j = i; j != n; ++ j) {
if (j == i)
nTempProduct = A[i];
else
nTempProduct *= A[j];
if (nTempProduct >= subArrayProduct)
subArrayProduct = nTempProduct;
// else
// break; //为了少计算后面的乘积
}
}
return subArrayProduct;
}
int maxProduct1(int A[], int n)
{
assert(n > 0);
if (n <= 0)
return 0;
if (n == 1)
return A[0];
int max_local = A[0];
int min_local = A[0];
int global = A[0];
for (int i = 1; i != n; ++ i) {
int max_copy = max_local;
max_local = MAX(MAX(A[i] * max_local, A[i]), A[i] * min_local);
min_local = MIN(MIN(A[i] * max_copy, A[i]), A[i] * min_local);
global = MAX(global, max_local);
}
return global;
}
int maxSubArray(int A[], int n)
{
assert(n > 0);
if (n <= 0)
return 0;
int global = A[0];
int local = A[0];
for(int i = 1; i != n; ++ i) {
local = MAX(A[i], local + A[i]);
global = MAX(local, global);
}
return global;
}
// int main()
// {
// int A[5] = {2,3,-2,-5,6};
// cout << maxSubArray(A, 5);
// cout << maxProduct1(A, 5);
// return 0;
// }