最大连续子序列之和问题

#include
using namespace std;

int n=6;
//穷举法
void MaxSubsequenceSum1(int a[])
{
	int MaxSum=0;
	int ThisSum;
	int start,end;
	for(int i=0;i<n;i++)
	{
		for(int j=i;j<n;i++)
		{
			ThisSum=0;
			for(int k=i;k<=j;k++)
			{
				ThisSum+=a[k];
			}
			if(ThisSum>MaxSum)
			{
				MaxSum=ThisSum;
				start=i;
				end=j;
			}
		}
	}
	cout<<"MaxSum: "<<MaxSum<<endl;
	cout<<"start: "<<start<<endl;
	cout<<"end: "<<end<<endl;

}


void MaxSubsequenceSum2(int a[])
{
	int MaxSum=0;
	int ThisSum;
	int start,end;
	for(int i=0;i<n;i++)
	{
		ThisSum=0;
		for(int j=i;j<=n;i++)
		{
			ThisSum+=a[j];
			if(ThisSum>MaxSum)
			{
				MaxSum=ThisSum;
				start=i;
				end=j;
			}
		}
	}
	cout<<"MaxSum: "<<MaxSum<<endl;
	cout<<"start: "<<start<<endl;
	cout<<"end: "<<end<<endl;

}
void MaxSubsequenceSum3(int a[])
{
	int MaxSum=0;
	int ThisSum;
	int start,end;
	ThisSum=0;
	for(int i=0,j=0;j<n;j++)
	{
		ThisSum+=a[j];
		if(ThisSum>MaxSum)
		{
			MaxSum=ThisSum;
			start=i;
			end=j;
		}
		else if(ThisSum<0)
		{
			i=j+1;
			ThisSum=0;
		}
	}
	cout<<"MaxSum: "<<MaxSum<<endl;
	cout<<"start: "<<start<<endl;
	cout<<"end: "<<end<<endl;

}
int main()
{
   int a[]={1,-3,4,-2,-1,6};
   //MaxSubsequenceSum1(a);
   //MaxSubsequenceSum2(a);
   MaxSubsequenceSum3(a);
	return 0;
}

不建议使用函数1,2,时间复杂度高(我的电脑运行不出结果)

你可能感兴趣的:(算法)