BJUTACM 1032:最大子段和

最大字段和问题可以说是最经典的动态规划问题之一,自己暂时认为如果采用普通方法时间复杂度可能会高达O(n!) (纯属本菜鸡猜测Orz)

但是如果采用动态规划方法,只需要遍历一次 即时间复杂度为O(n)即可解决这一问题

其基本思想是,采用两个变量,假设为temp 和max,temp每次增加入新的元素,之后首先和max进行比较,如果大于max则替换,如果加入新的元素后,temp元素小于了0,则此时开始,如果单纯加入下一个元素,会比从现在的temp开始加入一个新的元素还大,所以如果temp元素小于0,需要把temp元素重新设置为0

如此操作直到全部读完,时间复杂度O(n)

在其中可能比较麻烦的是如果全是负数的情况,这时候可以用第一位初始化max 或者把max设置为一极小值

题目链接

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <cstring>
#include <cmath>
#include <cstdlib>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

int main(int argc, char** argv) {
	int n;
	scanf("%d",&n);
	long max = -999999999;
	scanf("%ld",&max);
	long temp = 0;
	if(max>0)
	{
		temp = max;
	}
	else if(max<0)
	{
		temp = 0;
	}
	
	
	for(int i=1;i<n;i++)
	{
		long a;
		scanf("%ld",&a);
		temp += a;

		if(temp>max)
		{
			max = temp;
		}
		if(temp<0)
		{
			temp = 0;
			continue; 
		}
	 } 
	printf("%ld",max);
	//system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值