分治最大子数组

Posted cccv

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分治最大子数组相关的知识,希望对你有一定的参考价值。

 1     struct A
 2     {
 3         int maxright;   // 记录右边最大子数组的下标
 4         int maxleft;    // 记录左边最大子数组的下标
 5         int sum;        // 记录数组下标maxleft--maxright的元素和
 6     };
 7 
 8 void Solution::maxSubarray(const vector<int>& vec)
 9 {
10     int left = 0;
11     int right = vec.size() - 1;
12     A result = findMaxSubarr(vec, left, right);
13     cout << "left_index:" << result.maxleft << ", ";
14     cout << "right_index:" << result.maxright <<", " ;
15     cout << "sum = " << result.sum << endl;
16 }
17 
18 Solution::A Solution::findMaxSubarr(const vector<int>& vec,
19         int left, int right)
20 {
21     if(left == right)    
22     {
23         // base case: only one element
24         A maxsubarr;
25         maxsubarr.maxleft = left;
26         maxsubarr.maxright = right;
27         maxsubarr.sum = vec[left];
28         return maxsubarr;
29     } else
30     {
31         int mid = (left + right) / 2;
32         A leftarr = findMaxSubarr(vec, left, mid);
33         A rightarr = findMaxSubarr(vec, mid+1, right);
34         A crossarr = findCrossSubarr(vec, left, mid, right);
35         if(leftarr.sum >= rightarr.sum && leftarr.sum >= crossarr.sum)
36             return leftarr;
37         else if(rightarr.sum >= leftarr.sum && 
38                 rightarr.sum >= crossarr.sum)
39             return rightarr;
40         else
41             return crossarr;
42     }
43 }
44 
45 Solution::A Solution::findCrossSubarr(const vector<int>& vec, 
46         int left, int mid, int right)
47 {
48     int leftSum = INT_MIN;
49     int sum = 0;
50     A maxsubarr;
51     maxsubarr.maxleft = 0;
52     for(int i = mid; i >= left; i--)
53     {
54         sum = sum + vec[i];
55         if(sum > leftSum)
56         {
57             leftSum = sum;
58             maxsubarr.maxleft = i;
59         }
60         
61     }
62 
63     int rightsum = INT_MIN;
64     sum = 0;
65     for(int j = mid+1; j <= right; j++)
66     {
67         sum = sum + vec[j];
68         if(sum > rightsum)
69         {
70             rightsum = sum;
71             maxsubarr.maxright = j;
72         }
73     }
74     maxsubarr.sum = leftSum + rightsum;
75     return maxsubarr;
76 }

 

以上是关于分治最大子数组的主要内容,如果未能解决你的问题,请参考以下文章

分治——最大数组和

分治最大子数组

分治策略之最大子数组问题

分治策略---求最大子数组

最大子数组-经典动态规划+分治算法

分治算法 ------最大子段和