![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c33e932bef81cb64d99f009f62fd07e5.png)
#include<stdio.h>
#define N 100000
int MaxSubseqSum(int a[],int size);
int main(void)
{
int k=0,arr[N],result;
scanf("%d",&k);
for(int i=0;i<k;i++){
scanf("%d",&arr[i]);
}
result = MaxSubseqSum(arr,k);
printf("%d",result);
}
int MaxSubseqSum(int a[],int size){
int thisMax=0,maxSum=0;
int i,j;
for(i=0;i<size;i++){
thisMax =a[i];
for(j=i+1;j<size;j++){
thisMax +=a[j];
if(thisMax > maxSum){
maxSum = thisMax;
}
}
}
return maxSum;
}
分治方法处理最大子序列
#include<stdio.h>
#define N 100000
int MaxSubseqSum(int a[],int minIndex,int maxIndex);
int main(void)
{
int k=0,arr[N],result;
scanf("%d",&k);
for(int i=0;i<k;i++){
scanf("%d",&arr[i]);
}
result = MaxSubseqSum(arr,0,k-1);
printf("%d",result);
}
int MaxSubseqSum(int a[],int minIndex,int maxIndex){
if(minIndex == maxIndex){
return a[minIndex];
}
int middle = (minIndex+maxIndex)/2;
int leftMax=0,rightMax=0,middleMax=0,tempMax=0,i=0;
leftMax = MaxSubseqSum(a,minIndex,middle);
rightMax = MaxSubseqSum(a,middle+1,maxIndex);
tempMax = leftMax;
middleMax = leftMax;
for(i=middle+1;i<=maxIndex;i++){
tempMax += a[i];
if(tempMax > middleMax){
middleMax = tempMax;
}
}
return (leftMax>middleMax?leftMax:middleMax) > rightMax ? (leftMax>middleMax?leftMax:middleMax) : rightMax;
}
在线处理的方法处理最大子序列
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/99e52beb3c20cf54fbb57d513f377abd.png)
#include<stdio.h>
#define N 100000
int MaxSubseqSum(int a[],int size,int *indexMin,int *indexMax);
int main(void)
{
int k=0,a[N],result,indexMin,indexMax;
scanf("%d",&k);
for(int i=0;i<k;i++){
scanf("%d",&a[i]);
}
result = MaxSubseqSum(a,k,&indexMin,&indexMax);
if(result <0){
result = 0;
indexMin =0;
indexMax =k-1;
}
printf("%d %d %d",result,a[indexMin],a[indexMax]);
}
int MaxSubseqSum(int a[],int size,int *indexMin,int *indexMax){
int thisMax=0,maxSum=0,i,indexMi=0;
*indexMin =0;
*indexMax =0;
thisMax = 0;
maxSum = a[0];
for(i=0;i<size;i++){
thisMax += a[i];
if(thisMax > maxSum){
maxSum = thisMax;
*indexMax = i;
*indexMin = indexMi;
}
if(thisMax < 0){
thisMax = 0;
indexMi = i+1;
}
}
return maxSum;
}