最大字段和问题可以说是最经典的动态规划问题之一,自己暂时认为如果采用普通方法时间复杂度可能会高达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;
}