1050 循环数组最大子段和
基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
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
题解:
参考相关讨论。
有两种可能,第一种为正常从[1 - n]序列中的最大子字段和;第二种为数组的total_sum - ([1-n]序列中的最短序列和)
最后结果为 max { 第一种, 第二种}。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 5e5+100;
LL s[maxn];
int main()
{
LL N;
cin>>N;
LL total_sum=0;
for(int i=1;i<=N;i++)
{
cin>>s[i];
total_sum+=s[i];
}
LL summax=0,sum1=0,summin=0,sum2=0;
for(int i=1;i<=N;i++)
{
sum1=max(sum1,(LL)0)+s[i];
summax=max(summax,sum1);
sum2=min(sum2,(LL)0)+s[i];
summin=min(summin,sum2);
}
LL ans=max(summax,total_sum-summin);
cout<<ans<<endl;
return 0;
}