分治法求最大子段和

问题分析:(直接截的PPT) 

 

 

 

 代码如下:

 1 #include <iostream>
 2 #include <math.h>
 3 using namespace std;
 4 //寻找最大子段和
 5 int MaxSum(int a[], int left, int right) {
 6     int sum = 0, midsum = 0, leftsum = 0, rightsum = 0;
 7     if (left == right) sum = a[left];
 8     else {
 9         //划分
10         int center, lefts, rights, s1, s2, i;
11         center = (left + right) / 2;
12         leftsum = MaxSum(a, left, center);
13         rightsum = MaxSum(a, center+1, right);
14         //情况3
15         s1 = 0;
16         lefts = 0;
17         for (i = center; i >= left; i--) {
18             lefts = lefts + a[i];
19             if (lefts > s1) s1 = lefts;
20         }
21         s2 = 0;
22         rights = 0;
23         for (i = center + 1; i <= right; i++) {
24             rights = rights + a[i];
25             if (rights > s2) s2 = rights;
26         }
27         midsum = s1 + s2;
28         //寻找最大值
29         if (leftsum > rightsum) sum = leftsum;
30         else sum = rightsum;
31         if (sum < midsum) sum = midsum;
32     }
33     return sum;
34 }
35 int main() {
36     int a[10];
37     cout << "请依次输入十个数" << endl;
38     int i, sum;
39     for (i = 0; i < 10; i++) cin >> a[i];
40     cout << "输入完成!" << endl;
41     int left = 0, right = 9;
42     sum = MaxSum(a, left, right);
43     cout << "最大子段和为" << sum << endl;
44     return 0;
45 }

时间复杂度:O(nlog2n)

 

posted @ 2020-05-21 17:25  打不死的小王  阅读(533)  评论(0编辑  收藏  举报