#include<stdio.h>
int max_sub_sum(int a[] , int left , int right);
int max_sum3(int a[] , int n)
{
int k = max_sub_sum(a,0,n);
// return (max_sub_sum(a,1,n));
printf("%d\n",k);
return k;
}
int main(void)
{
int a[7] = {-2,11,-4,13,-5,-2};
int n = 6;
int k = max_sum3(a , n);
printf("%d\n",k);
return 0;
}
int max_sub_sum(int a[] , int left , int right)
{
int center,i,j,sum,left_sum,right_sum,s1,s2,lefts,rights;
if(left == right)
{
if(a[left]>0)
return (a[left]);
else
return 0;
}
else
{
center = (left + right)/2;
left_sum = max_sub_sum(a , left , center);
right_sum = max_sub_sum(a , center+1 , right);
}
s1 = 0;
lefts = 0;
for(i = center ; i >=left ; i--)
{
lefts = lefts+a[i];
if(lefts > s1)
{
s1 = lefts;
}
}
s2 = 0;
rights = 0;
for(i = center+1 ; i <= right ; i++)
{
rights = rights+a[i];
if(rights > s2)
{
s2 = rights;
}
}
if( (s1+s2 < left_sum) && (right_sum < left_sum))
{
return left_sum;
}
else if((s1+s2 < right_sum) )
{
return right_sum;
}
else
return (s1+s2);
}
求数列的最大字段和 算法
最新推荐文章于 2024-03-21 12:29:57 发布