题目大意:给你n个整数,求出其中长度不超过m的最大字段和。
题解:单调队列维护前缀和最小值,然后用当前值减去当前有效最小值即可
C++ Code:
#include<cstdio> using namespace std; int n,m; int q[501000],sum[501000],h,t,ans; int s[501000]; int max(int a,int b){return a>b?a:b;} int main(){ scanf("%d%d",&n,&m); for (int i=1;i<=n;i++)scanf("%d",&s[i]); q[h=t=1]=1; for (int i=1;i<=n;i++){ sum[i]=sum[i-1]+s[i]; while (h<=t&&sum[i]<sum[q[t]])t--; q[++t]=i; if (i-q[h]>=m)h++; ans=max(sum[i]-sum[q[h]],ans); } printf("%d ",ans); return 0; }