(线性dp,最大连续和)Max Sequence

Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N).


You should output S.

Input

The input will consist of several test cases. For each test case, one integer N (2 <= N <= 100000) is given in the first line. Second line contains N integers. The input is terminated by a single line with N = 0.

Output

For each test of the input, print a line containing S.

Sample Input

5
-5 9 -5 11 20
0

Sample Output

40
题目就是简单的数学题目,找到前面一段的最大字段和后面的最大字段之和最大,从头开始遍历,然后在从后面遍历一遍相加求最大,是一个简单题目。
AC代码以下:
复制代码
#include<algorithm>
#include<iostream>
using namespace std;
const int N=1e5+10;
int dp[N],dp1[N],aa[N],dp2[N];

int main(){
    int n;
    while(cin>>n,n!=0){
        int i,temp=-9999,sum=0,ans;
        for(i=1;i<=n;i++)
            cin>>aa[i];
       for(i=1;i<n;i++){//dp为滚动数组,存最大字段和,dp1存到当前位置的最大字段;
            dp1[i]=max(dp1[i-1]+aa[i],aa[i]);
            temp=max(temp,dp1[i]);
            dp[i]=temp;
        }
        sum=0,ans=-9999,temp=-9999;
        for(i=n;i>1;i--){//从后往前找最大字段用temp来保存
            sum+=aa[i];
            temp=max(temp,sum);
            ans=max(ans,temp+dp[i-1]);
//            dp2[i]=max(dp2[i+1],sum);
//            ans=max(ans,dp2[i]+dp[i-1]);
            if(sum<0)sum=0;
        }
        cout<<ans<<endl;
    }
    return 0;
}
复制代码

WA代码:

复制代码
#include<algorithm>
#include<iostream>
using namespace std;
const int N=1e5+10;
int dp[N],dp1[N],aa[N],dp2[N];

int main(){
    int n;
    while(cin>>n,n!=0){
        int i,temp=-9999,sum=0,ans;
        for(i=1;i<=n;i++)
            cin>>aa[i];
       for(i=1;i<n;i++){
            dp1[i]=max(dp1[i-1]+aa[i],aa[i]);
            temp=max(temp,dp1[i]);
            dp[i]=temp;
        }
        sum=0,ans=-9999,temp=-9999;
        for(i=n;i>1;i--){//仅仅将上部分的注释改了一下,其实大致思路都是一样的,但是poj过不去就很迷人,无论是打印一次temp和dp1都是相同的就是拉跨,当时网络上都是一个sum变量解决滚动的问题,终究还是没找到问题原因就是了
//            sum+=aa[i];
//            temp=max(temp,sum);
//            ans=max(ans,temp+dp[i-1]);
            dp2[i]=max(dp2[i+1],sum);
            ans=max(ans,dp2[i]+dp[i-1]);
//            if(sum<0)sum=0;
        }
        cout<<ans<<endl;
    }
    return 0;
}
复制代码

 

posted @   JerryTang菜菜  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示