蒜厂年会(一个圆形数组,问最大连续和是多少)思维

转载出处:https://blog.csdn.net/qq_41410799/article/details/87436835

因为求的结果是连续的,所以可能是包含环和不包含环的,包含环的就是sum-minsum,否则maxsum。 这道题也可以建一个2n的序列,然后注意边界。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define LL long long
using namespace std;
const int maxn=300005;
const int mod=100000007;
int n;
LL a[maxn];
int main()
{
    scanf("%d",&n);
    LL sum=0;
    for(int i=0;i<n;i++)
    {
        scanf("%lld",&a[i]);
        sum+=a[i];
    }
    LL maxsum,minsum;
    maxsum=minsum=0;

    LL maxtemp,mintemp;
    maxtemp=mintemp=0;
    for(int i=0;i<n;i++)
    {
        maxtemp+=a[i];
        mintemp+=a[i];
        maxsum=max(maxsum,maxtemp);
        minsum=min(minsum,mintemp);
        if(maxtemp<0)
            maxtemp=0;
        if(mintemp>0)
            mintemp=0;
    }
    cout << max(maxsum,sum-minsum) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wwwlps/article/details/88584423