Max Sequence
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
5
-
描述
-
Give you N integers a1, a2 ... aN (|ai| <=1000, 1 <= i <= N).
You should output S.
-
输入
- 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. 输出
- For each test of the input, print a line containing S. 样例输入
-
5 -5 9 -5 11 20 0
样例输出
-
40
解题思路:最大子串和的变形题,利用dp的思想,dp[i][0]表示从从左边扫,以i结尾的最大子串和,同理dp[i][1]表示从右边扫,以i结尾的最大子串和。
首先要明白这样做的目的,我们是想要枚举分界线k,那么两个串就被分成两段1-(k-1)和k-n,我们只要找到这两段的最大子串和,加起来即可。
光知道dp[i]还不够,因为算的是以i结尾,我们有可能不会去取第i个数,所以还需要再用一次dp的思想,去解决前i个数内的最大子串和,同样需要知道从左扫的L[i]和从右边扫的R[i]。。都是比较简单的dp。。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 100005; const int inf = 0x3f3f3f3f; int n,a[maxn]; int dp[maxn][2]; int L[maxn],R[maxn]; int main() { while(scanf("%d",&n),n) { memset(L,0,sizeof(L)); memset(R,0,sizeof(R)); for(int i = 1; i <= n; i++) scanf("%d",&a[i]); dp[1][0] = a[1]; for(int i = 2; i <= n; i++) { dp[i][0] = a[i]; dp[i][0] = max(dp[i][0],dp[i-1][0] + a[i]); } dp[n][1] = a[n]; for(int i = n - 1; i >= 1; i--) { dp[i][1] = a[i]; dp[i][1] = max(dp[i][1],dp[i+1][1] + a[i]); } L[1] = dp[1][0]; for(int i = 2; i <= n; i++) L[i] = max(L[i-1],dp[i][0]); R[n] = dp[n][1]; for(int i = n - 1; i >= 1; i--) R[i] = max(R[i+1],dp[i][1]); int ans = -inf; for(int i = 2; i < n; i++) ans = max(ans,L[i-1] + R[i]); printf("%d\n",ans); } return 0; }