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
 
Source
***************************************************************************************
求最大子段和问题,先正求再倒求,代码有些烦杂
***************************************************************************************
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<vector>
 6 #include<algorithm>
 7 #include<stack>
 8 using namespace std;
 9 const  int inf=-999999999;
10 int a[1001];
11 int sum[1001]={0};
12 int dp1[1001];
13 int dp2[1001];
14 int n,i,j,k;
15 int num;
16 int main()
17 {
18     while(cin>>n&&n)
19     {
20         sum[0]=0;
21         for(i=1;i<=n;i++)
22        {
23          cin>>a[i];
24          sum[i]=sum[i-1]+a[i];
25        }
26     num=-999999999;
27     for(i=1;i<=n;i++)
28     {
29         dp1[i]=a[i];
30     }
31     dp1[0]=0;
32     for(i=1;i<=n;i++)
33      {
34          for(k=1;k<=i;k++)
35           if(dp1[i]<dp1[k]+sum[i]-sum[k])
36             dp1[i]=dp1[k]+sum[i]-sum[k];
37          for(j=i+1;j<=n;j++)
38            {
39             for(k=j;k<=n;k++)
40             if(dp2[j]<sum[k]-sum[j])
41               dp2[j]=sum[k]-sum[j];
42             if(num<dp1[i]+dp2[j])
43                num=dp1[i]+dp2[j];
44             }
45 
46      }
47      cout<<num<<endl;
48     }
49      return 0;
50 
51 }
View Code

转载于:https://www.cnblogs.com/sdau--codeants/p/3258846.html

猜你喜欢

转载自blog.csdn.net/weixin_34128839/article/details/93432950
max