链接:http://acm.hdu.edu.cn/showproblem.php?pid=1231
思路:最大连续子序列其实可以发现开始的那个数一定不是负数,从输入开始:
ma:记录每次的最大值
res :记录每次加上输入的值后的总值,以res判定是否大于原先的最大值,如果是的话,将该点加入,判定res是否小于0,如果是的话则将res至0,并重新从下一点开始。(一开始想如果全部是负数该怎么办,但全部是负数的话,就找最大的那个负数就好了)
代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int INF = -1e6;
int main()
{
int n,a[10010];
while(true)
{
cin >> n;
if(n == 0) break;
int res=0,st,en,Maxres=INF,tempst=0;
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
res += a[i];
if(res > Maxres){
Maxres = res;
en = i;
st = tempst;
}
if(res < 0)
{
res = 0;
tempst = i+1;
}
}
if(Maxres < 0)
{
Maxres = 0;
st=0;
en=n-1;
}
printf("%d %d %d\n",Maxres,a[st],a[en]);
}
return 0;
}