分治法即计算左侧所有值的和,计算右侧所有值的和,计算所有值的和,判断哪个最大,最大值作为输出。
1 #include <iostream> 2 #include<string.h> 3 using namespace std; 4 5 int MaxSum(int a[],int left,int right){ 6 int leftSum=0,rightSum=0,sum=0,midSum=0; 7 int center,s1,s2,lefts,rights; 8 if(left==right)//序列长度为1,直接输出 9 sum=a[left]>0?a[left]:0; 10 else{ 11 center=(left+right)/2; 12 leftSum=MaxSum(a,left,center); 13 rightSum=MaxSum(a,center+1,right); 14 s1=0; 15 lefts=0; 16 for(int i=center;i>=left;i--){//计算左侧所有值的和 17 lefts+=a[i]; 18 if(lefts>s1) 19 s1=lefts; 20 } 21 s2=0; 22 rights=0; 23 for(int i=center+1;i<=right;i++){//计算右侧所有值的和 24 rights+=a[i]; 25 if(rights>s2) 26 s2=rights; 27 } 28 midSum=s1+s2;//所有值的和 29 if(leftSum>midSum) 30 sum=leftSum; 31 else 32 sum=midSum; 33 if(rightSum>sum) 34 sum=rightSum; 35 } 36 return sum; 37 } 38 int main() 39 { 40 int T,N; 41 int a[100]; 42 scanf("%d",&T); 43 while(T--){ 44 memset(a,0,sizeof(a)); 45 scanf("%d",&N); 46 for(int i=0;i<N;i++) 47 scanf("%d",&a[i]); 48 int result=MaxSum(a,0,N-1); 49 printf("%d",result); 50 } 51 return 0; 52 }