-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.cpp
72 lines (58 loc) · 976 Bytes
/
3.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
*求子数组的最大和(数组)
*/
#include <iostream>
using namespace std;
/*
int GetMax(int *a, int n)
{
int i;
bool flag = true; //判别是否全部是负数
int max = a[0];
for (i = 0; i < n; i++) {
if (a[i] >= 0) {
flag = false;
break;
}
if (a[i] > max)
max = a[i];
}
if (flag)
return max;
int temp = 0;;
int maxSubSum = 0;
for (i = 0; i < n; i++) {
temp += a[i];
if (temp < 0)
temp = 0;
else {
if (temp > maxSubSum)
maxSubSum = temp;
}
}
return maxSubSum;
}*/
int GetMax(int *a, int n)
{
int i, temp = 0;;
int maxSubSum = (1<<31);
for (i = 0; i < n; i++) {
temp += a[i];
if (temp > maxSubSum)
maxSubSum = temp;
if (temp < 0)
temp = 0;
}
return maxSubSum;
}
int main()
{
int a[] = {1,-2,3,10,-4,7,2,-5};
cout << GetMax(a, 8) << endl;
int b[] = {-1,-6,-7,0};
int c[] = {-1,-6,-3};
int f[] = {-1,2};
cout << GetMax(b, 4) << " " << GetMax(c,3) << endl;
cout <<GetMax(f,2) << endl;
return 0;
}