题目链接:
https://www.acwing.com/problem/content/1089/
思路见下图:
代码:
#include<iostream>
using namespace std;
#define int long long
const int N=1e5+10;
int f[N],n,k,s[N];
int q[N];
int g(int i){
if(!i)return 0;
return f[i-1]-s[i];
}
signed main(){
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>s[i];
s[i]+=s[i-1];
}
int hh=0,tt=0;
for(int i=1;i<=n;i++){
if(i-q[hh]>k)hh++;
f[i]=max(f[i-1],g(q[hh])+s[i]);
while(hh<=tt&&g(q[tt])<=g(i))tt--;
q[++tt]=i;
}
printf("%lld",f[n]);
}