最大子段和

最大子段和


#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;

typedef struct BestNode
{
	int l, r;//和最大子段的最左指针和最右指针
	int maxs;
}Best;
class MAXSum
{
public:
	MAXSum()
	{
		cin >> n;
		num.assign(n + 1, 0);
		for (int i = 1; i <= n; i++)
		{
			int in;
			cin >> in;
			num[i] = in;
		}
		b0 = { 0 };
	}
	//朴素法,简洁易懂O(n^2)
	void MaxSum1()
	{
		for (int i = 1; i <= n; i++)
		{  
			int sum = 0;
			for (int j = i; j <= n; j++)
			{
				sum += num[j];
				if (sum > b0.maxs)
				{
					b0 = { i , j , sum };
				}
			}
		}
	}
	//分治法 O(nlogn)
	void  MaxSum2(int i , int j , Best& b)
	{
		if (i != j)
		{
			int mid = (i + j) / 2;
			Best b1 = { 0 };
			Best b2 = { 0 };
			Best b3 = { 0 };
			MaxSum2(i, mid , b1);
			MaxSum2(mid+1, j , b2);
			int temp = 0;
			b3.l = mid + 1;
			for(int k = mid; k >= i; k--)
			{
				temp += num[k];
				if (temp > b3.maxs)
				{
					b3.maxs = temp;
					b3.l = k;
				}
			}
			temp = b3.maxs;
			b3.r = mid + 1;
			for (int k = mid + 1; k <= j; k++)
			{
				temp += num[k];
				if (temp > b3.maxs)
				{
					b3.maxs = temp;
					b3.r = k;
				}
			}
			if (b3.maxs == 0)
			{
				b3.l = b3.r = 0;
			}

			//求b1 , b2 , b3中的最大值
			if (b3.maxs < b1.maxs)
			{
				b3 = b1;
			}
			if (b3.maxs < b2.maxs)
			{
				b3 = b2;
			}
			b = b3;
		}
		else
		{
			if (num[i] > 0)
			{
				b = { i , i , num[i] };
			}
			else
			{
				b = { 0 };
			}
		}
		
	}
	//动态规划法O(n)
	void MaxSum3()
	{
		Best b = { 0, 0,0 };
		Best temp = b;
		for (int i = 1; i <= n; i++)
		{
			//以i结尾的所有连续子段中和最大的那个
			b.r = i;
			if (b.maxs > 0)
			{
				b.maxs += num[i];
			}
			else
			{
				b.maxs = num[i];
				b.l = i;
				if (num[i] < 0)
				{
					b.l = b.r = 0;
				}
			}
			if (temp.maxs < b.maxs)
			{
				temp = b;
			}
		}
		b0 = temp;
	}
	void print()
	{
		cout << "最大子段和:" << b0.maxs << endl;;
		cout << "{ ";
		for (int i = b0.l; i < b0.r; i++)
		{
			cout << num[i] << ",";
		}
		cout << num[b0.r]<<" }"<< endl;

	}
public:
	vector<int> num;
	int n;
	Best b0;
};
MAXSum MS;
int main()
{
	//MS.MaxSum1();
	//MS.MaxSum2(1, MS.n, MS.b0);
	MS.MaxSum3();
	MS.print();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值