最大连续和
从长度为n的序列中取一段长度不超过m的非空连
正文
/*
原题:T1598 「一本通 5.5 例 2」最大连续和
题意:从长度为 n 的序列中取一段长度不超过 m 的非空连续子段,使其和最大。
思路:前缀和 s[i],答案 = max_{i}(s[i] - min_{j∈[i-m,i-1]} s[j]);
用递增单调队列在窗口内维护最小的 s[j],O(1) 取得最小值。
复杂度:时间 O(n),空间 O(n)。
易错点:子段非空且长度 ≤m;j 可取 0(空前缀)表示子段从 1 开始;用 long long 防溢出。
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,m;
cin>>n>>m;
vector<long long> s(n+1,0);
for(int i=1;i<=n;i++){
long long x;
cin>>x;
s[i]=s[i-1]+x;
}
deque<int> q;
q.push_back(0);
long long ans=LLONG_MIN;
for(int i=1;i<=n;i++){
while(!q.empty()&&q.front()<i-m){
q.pop_front();
}
ans=max(ans,s[i]-s[q.front()]);
while(!q.empty()&&s[q.back()]>=s[i]){
q.pop_back();
}
q.push_back(i);
}
cout<<ans<<'\n';
return 0;
}
一本通·提高篇的其它内容
- 活动安排
- 种树
- 喷水装置
- 加工生产调度
- 智力大冲浪
- 数列极差
- 数列分段
- 线段
- 家庭作业
- 钓鱼
- 糖果传递
- 愤怒的牛
- Best Cow Fences
- 曲线
- 数列分段 II
- 扩散
- 灯泡
- 传送带
- 数的划分
- 生日蛋糕
- 小木棍
- Addition Chains
- 埃及分数
- 平板涂色
- 质数方阵
- 靶形数独
- 电路维修
- 魔板
- Knight Moves
- 棋盘游戏
- Keyboarding
- 移动玩具
- 山峰和山谷
- Oulipo
- 图书管理
- Power Strings
- Seekthe Name, Seek the Fame
- Friends
- A Horrible Poem
- Beads
- Antisymmetry
- 门票
- 收集雪花
- 剪花布条
- Power Strings
- Radio Transmission
- OKR-Periods of Words
- 似乎在梦中见过的样子
- Censoring
- Phone List
- The XOR Largest Pair
- Nikitosh 和异或
- Immediate Decodability
- L 语言
- Secret Message 秘密信息
- 背单词
- The Xor-longest Path
- Keywords Search
- 玄武密码
- Censoring