51nod 循环数组最大子段和

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。

Input

 
   

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

Output

 
   

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

Input示例

 
   

6 -2 11 -4 13 -5 -2

Output示例

 
   

20

因为这里需要考虑到循环问题 也就是环状最大子段和

两种情况产生最大子段和:一种是在数串的中间产生,一种是由首尾产生
在中间产生的情况相信大家都可以计算出来了,那么如何应对首尾产生的情况呢?

还是先遍历一遍,求出一个普通的最大子段和,顺便求出最小字段和与数串的总和
用数串的总和减去最小字段和就是由首尾产生的最大子段和了

但是要和普通的最大字段和比较一下,选最大即可。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
#include <cmath>
using namespace std;
int T,A[50005];
int main()
{
   ios::sync_with_stdio(false);
   cin>>T;
   for(int i=0;i<T;i++)
    cin>>A[i];
    long long xiao=9999999,da=-9999999,ans1=0,ans2=0,sum=0;
   for(int i=0;i<T;i++)
   {
        if(ans1+A[i]>A[i])  
        {
            ans1+=A[i];
        }
        else
        {
            ans1=A[i];
        }
        if(ans2+A[i]<A[i])
        {
            ans2+=A[i];
        }
        else
        {
            ans2=A[i];
        }
        if(ans2<xiao) xiao=ans2;
        if(ans1>da) da=ans1;
        sum+=A[i];
   }
   if(sum-xiao>da) da=sum-xiao;
    cout<<da<<endl;
    return 0;
}
// 7 2 -4 3 -1 2 -4 3

猜你喜欢

转载自blog.csdn.net/whyckck/article/details/80199245
今日推荐