复制一遍 a 数组,然后处理前缀和。单调队列模板求出当前位置 i 的前 n 个位置的最小前缀和的位置,记为 id_i,然后枚举 2 \times n 个位置。每个位置更新 mx=\max(mx,sum_i-sum_{id_i}),最后的答案即为 mx。注意刚开始要在单调队列中放入 0 元素。
AC 代码
#include<bits/stdc++.h>
using namespace std;
struct node{
int id;
long long sum;
};
long long sum[400010];
long long a[400010];
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
a[i+n]=a[i];
}
for(int i=1;i<=2*n;i++){
sum[i]=sum[i-1]+a[i];
}
deque<node>q;
q.push_back({0,0});
long long mx=-1e18;
for(int i=1;i<=2*n;i++){
while(!q.empty() && i-(q.front()).id>n){
q.pop_front();
}
mx=max(mx,sum[i]-(q.front()).sum);
while(!q.empty() && (q.back()).sum>sum[i]){
q.pop_back();
}
q.push_back({i,sum[i]});
}
cout<<mx;
return 0;
}