最大和子序列

#include <iostream>
using namespace std;

int MaxSubsequenceSum1(int* array,int left,int right); //O(nlogn)
int MaxSubsequenceSum2(int* array,int left,int right); //O(n)
int MaxBorderSum(int* array,int begin,int end);
int MaxThreeNum(int x,int y,int z);
int array[8]={4,-3,5,-2,-1,2,6,-2};

int main()
{
	cout << MaxSubsequenceSum2(array,0,9) << endl;
	if(cin.get()=='\n')
		return 0;
}

int MaxSubsequenceSum1(int* array,int left,int right)
{
	if(left==right)
		return array[left];
	int center=(left+right)/2;
	int LeftMaxSum=MaxSubsequenceSum1(array,left,center);
	int RightMaxSum=MaxSubsequenceSum1(array,center+1,right);
	int TheMaxBorderSum=MaxBorderSum(array,center,left)+MaxBorderSum(array,center+1,right);
	return MaxThreeNum(LeftMaxSum,RightMaxSum,TheMaxBorderSum);
}

//动态规划思想:
int MaxSubsequenceSum2(int* array,int left,int right)
{
	int ThisSum=0,MaxSum=0;
	for(int i=left;i<=right;++i)
	{
		ThisSum+=array[i];
		if(ThisSum<0)
			ThisSum=0;
		else if(ThisSum>MaxSum)
			MaxSum=ThisSum;
	}
	return MaxSum;
}

int MaxBorderSum(int* array,int begin,int end)
{
	int MaxBorderSum=0,BorderSum=0,MoreOrLess=0;
	if(begin==end)
		return array[begin];
	else if(begin<end)
		MoreOrLess=1;
	else if(begin>end)
		MoreOrLess=-1;
	int TheEnd=end+MoreOrLess;
	for(int i=begin;i!=TheEnd;i+=MoreOrLess)
	{
		BorderSum+=array[i];
		if(BorderSum>MaxBorderSum)
			MaxBorderSum=BorderSum;
	}
	return MaxBorderSum;
}

int MaxThreeNum(int x,int y,int z)
{
	return x>y?(x>z?x:z):(y>z?y:z);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值