-
Notifications
You must be signed in to change notification settings - Fork 430
/
分治算法.c
67 lines (63 loc) · 1.02 KB
/
分治算法.c
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
//分治算法
#include <stdio.h>
int MaxSubSum(int *a, int left, int right);
int MaxSum(int n, int *a);
int main()
{
int a[] = { -2, 11, -4, 13, -5, -2 };
for (int i = 0; i<6; i++)
{
printf("%d ", a[i]);
}
printf("\n");
printf("数组a的最大连续子段和为:%d\n", MaxSum(6, a));
return 0;
}
int MaxSubSum(int *a, int left, int right)
{
int sum = 0;
if (left == right)
{
sum = a[left]>0 ? a[left] : 0;
}
else
{
int center = (left + right) / 2;
int leftsum = MaxSubSum(a, left, center);
int rightsum = MaxSubSum(a, center + 1, right);
int s1 = 0;
int lefts = 0;
for (int i = center; i >= left; i--)
{
lefts += a[i];
if (lefts>s1)
{
s1 = lefts;
}
}
int s2 = 0;
int rights = 0;
for (int i = center + 1; i <= right; i++)
{
rights += a[i];
if (rights>s2)
{
s2 = rights;
}
}
sum = s1 + s2;
if (sum<leftsum)
{
sum = leftsum;
}
if (sum<rightsum)
{
sum = rightsum;
}
}
return sum;
}
int MaxSum(int n, int *a)
{
return MaxSubSum(a, 0, n - 1);
}