Algorithm idea:
Find the largest sub-segment sum through the idea of divide and conquer, and divide the number component into two parts equally, then the largest sub-segment sum will exist in three situations:
1. The largest sub-segment sum appears at the left end
2. The largest sub-segment sum appears At the right end
3. The largest sub-segment and straddling the left and right segments, the largest sub-segment sum is obtained by comparing the sizes
//最大子段和问题 p64
#include<stdio.h>
#include<iostream>
using namespace std;
int MaxSum(int a[],int left,int right);
int a[100];
int main(void)
{
int n,j;
scanf("%d",&n);
for(j=0;j<n;j++)
scanf("%d",&a[j]);
printf("%d",MaxSum(a,0,n-1));
return 0;
}
int MaxSum(int a[],int left,int right)
{
int sum=0,midSum=0,leftSum=0,rightSum=0;
int center,s1,s2,lefts,rights;
if(left==right)
sum=a[left];
else{
center=(left+right)/2;
leftSum=MaxSum(a,left,center); //情况1,最大字段和全部取左边元素
rightSum=MaxSum(a,center+1,right);//情况2,最大字段和全部取右边元素
s1=0;lefts=0; //情况3 最大子段和横跨中间
for(int i=center;i>=left;i--) //求出s1:从中间到左边的最大和
{
lefts+=a[i];
if(lefts>s1) s1=lefts;
}
s2=0;rights=0;
for(int j=center+1;j<=right;j++) //求出s2 从中间到右边的最大和
{
rights+=a[j];
if(rights>s2) s2=rights;
}
midSum=s1+s2; //横跨中间的最大字段和为s1+s2
if(midSum<leftSum) sum=leftSum;
else sum=midSum;
if(sum<rightSum) sum=rightSum; //取三者的较大者
}
return sum;
}