Maximum subsequence
Timelimit: 1 second memorylimit: 32 megabyte
Totalsubmit: 156 accepted: 42
Description
Given a sequence composed of N integers, integers are positive and negative, and two consecutive subsequences that do not overlap are found so that the integers and the largest of them are obtained. Both sub-sequences can be empty.
Input
Multiple Input groups. The first action N in each group indicates the length of the sequence. The second action n integers indicates the input sequence.
0 <n <= 1,000,000
Output
For each input group, only one integer is returned, indicating the maximum sum.
Sample Input
9
185-580-889 701 964-878 353-761 608
Sample output
2273
Hint
For example, the input sequence is (701 964) and (608), and the Integer Range is)
#include <iostream>#include <cstdio>using namespace std;const int INF=1000005;int s[INF],lt[INF],rt[INF],dp[INF];int main(){ //freopen("in.txt","r",stdin); int i,n; while(cin >> n) { for (i=1;i<=n;i++)scanf("%d",&s[i]); dp[n+1]=dp[0]=-INF; lt[0]=rt[n+1]=-INF; for (i=1;i<=n;i++)//正向 { dp[i] = max(dp[i-1]+s[i],s[i]); } for (i=1;i<=n;i++) { lt[i] = max(dp[i],lt[i-1]);// lt[i] = dp[i]; } for (i=n;i>=1;i--) //逆向 { dp[i] = max(dp[i+1]+s[i],s[i]); } for (i=n;i>=1;i--) { rt[i] = max(dp[i],rt[i+1]);// rt[i] = dp[i]; } int sum=-INF;//枚举 for (i=1;i<=n;i++) { sum = max(sum,lt[i]+rt[i+1]); } if(sum<=0) cout <<‘0‘ <<endl; else printf("%d\n",sum); } return 0;}
[Two-segment continuous non-duplicate sequence and maximum] dynamic planning