最大子序列和

#include<iostream>
using namespace std;
int maxarray1(int* a,int n)/////////
{
	int maxsum=0,thissum;
	for(int i=0;i<n;i++)
	{
		thissum=0;
		for(int j=0;j<n;j++)
		{
			thissum+=a[j];
			if(thissum>maxsum)
				maxsum=thissum;
		}
	}
	return maxsum;
}
int maxarray2(int*a,int left,int right)//////////////
{
	int mid=(left+right)/2;
	int maxleft=0,maxright=0,maxcross=0;
	if(left==right)
	{
		if(a[left]>0) return a[left];
		else return 0;
	}
	maxleft=maxarray2(a,left,mid);
	maxright=maxarray2(a,mid+1,right);
	int maxcrossleft=0,maxcrossright=0,crossl,crossr;
	int thiscrossleft=0,thiscrossright=0;
	for(crossl=mid;crossl>=left;crossl--)
	{
		thiscrossleft+=a[crossl];
		if(thiscrossleft>maxcrossleft)
			maxcrossleft=thiscrossleft;
	}
	for(crossr=mid+1;crossr<=right;crossr++)
	{
		thiscrossright+=a[crossr];
		if(thiscrossright>maxcrossright)
			maxcrossright=thiscrossright;
	}
	maxcross=maxcrossleft+maxcrossright;
	int maxsum;
	maxsum=maxleft>maxright?maxleft:maxright;
	maxsum=maxsum>maxcross?maxsum:maxcross;
	return maxsum;
}
int maxarray2(int *a,int n)//驱动maxarray(a,left,right)
{
	return maxarray2(a,0,n-1);
}
int maxarray3(int* a,int n)////////////
{
	int maxsum=0,thissum=0;
	for(int i=0;i<n;i++)
	{
		thissum+=a[i];
		if(thissum>maxsum) maxsum=thissum;
		else if(thissum<0) thissum=0;
	}
	return maxsum;
}

int main()
{
	int n;
	cin>>n;
	int*a=new int[n];
	for(int i=0;i<n;i++) cin>>a[i];
	cout<<maxarray3(a,n)<<endl;
	system("pause");
}

你可能感兴趣的:(最大子序列和)