Max Sequence
- 描述
-
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; }