算法导论-----最大子数组问题

Posted __迷途的羔羊

tags:

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

 1 #include"stdio.h"
 2 int findMaxCrossingSubarray(int a[],int low,int high);
 3 int findMaximumSubarray(int a[],int low,int high);
 4 int maxLeft,maxRight;
 5 int main()
 6 {
 7     int a[100] = {0,13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
 8     int maxSum;
 9     maxSum = findMaximumSubarray(a,1,16);
10     printf("%d %d\n",maxLeft,maxRight);
11     printf("%d\n",maxSum);
12     return 0;
13 }
14 int findMaxCrossingSubarray(int a[],int low,int high)
15 {
16     int i,j;
17     int mid;
18     int leftSum = -9999,rightSum = -9999;
19     int sum = 0;
20 
21     mid = (low + high) / 2;
22     for(i = mid;i>=1;i--)
23     {
24         sum = sum + a[i];
25         if(sum > leftSum)
26         {
27             leftSum = sum;
28             maxLeft = i;
29         }
30     }
31     sum = 0;
32     for(j = mid +1;j<=high;j++)
33     {
34         sum = sum + a[j];
35         if(sum > rightSum)
36         {
37             rightSum = sum;
38             maxRight = j;
39         }
40     }
41     return leftSum + rightSum;
42 }
43 int findMaximumSubarray(int a[],int low,int high)
44 {
45     int mid;
46     int leftSum,crossSum,rightSum;
47     if(high == low)
48         return a[low];
49     else
50     {
51         mid = (low + high) / 2;
52         leftSum = findMaximumSubarray(a,low,mid);
53         rightSum = findMaximumSubarray(a,mid + 1,high);
54         crossSum = findMaxCrossingSubarray(a,low,high);
55         if(leftSum >= rightSum && leftSum >= crossSum)
56             return leftSum;
57         else if(rightSum >= leftSum && rightSum >= crossSum)
58             return rightSum;
59         else
60             return crossSum;
61     }
62 }

 

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

算法导论-----最大子数组问题

算法导论最大子数组

文心一言 VS 讯飞星火 VS chatgpt (18)-- 算法导论4.1 5题

最大子数组问题

最大子数组问题

[算法导论]#6 堆排序