最大子序和III

N个整数组成的循环序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续的子段和的最大值(循环序列是指n个数围成一个圈,因此需要考虑a[n-1],a[n],a[1],a[2]这样的序列)。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。

输入

第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N+1行:N个整数 (-10^9 <= S[i] <= 10^9)

输出

输出循环数组的最大子段和。

输入样例

6
-2
11
-4
13
-5
-2

输出样例

20
#include <cmath>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
const int N=50010;
int a[N];
typedef long long LL;
LL getmax(int *a, int n){
    LL res=INT_MIN,s=0;
    for(int i=0;i<n;i++){
        if(s<0)s=0;
        s+=a[i];
        res=max(res,s);
    }
    return res;
}
int main() { 
    int n;
    LL sum=0;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
        sum+=a[i];
    }
    LL s1=getmax(a,n);
    for(int i=0;i<n;i++)a[i]=-a[i];
    LL s2=getmax(a,n);
    cout<<max(s1,sum+s2)<<endl;
    
    return 0;
}

 

posted @ 2019-07-20 15:41  YF-1994  阅读(117)  评论(0编辑  收藏  举报