解題思路
滑動長度 K 的窗,維護總和以及單調遞增、遞減的索引佇列,前端分別為最小、最大值。
每次移右端,移除佇列中被新值支配的尾端,再移除超過窗左界的前端。
窗分數為 sum-min-max,兩者即使相等仍各減一次。只在分數嚴格更大時更新答案,保留最早左端。
時間 O(N),空間 O(N),佇列最多 O(K)。
Step-by-step animation
教學例子:1、9、2,刪最小1與最大9,剩2。
步驟 1 / 3
步驟 1
1、9、2,刪最小1與最大9,剩2。
1
9
2
- 狀態
- 左端1,分數2
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, K;
cin >> n >> K;
vector<long long> a(n);
for (auto &x : a)
cin >> x;
deque<int> mn, mx;
long long s = 0, best = LLONG_MIN;
int pos = 0;
for (int i = 0; i < n; i++) {
s += a[i];
if (i >= K)
s -= a[i - K];
while (!mn.empty() && a[mn.back()] >= a[i])
mn.pop_back();
while (!mx.empty() && a[mx.back()] <= a[i])
mx.pop_back();
mn.push_back(i);
mx.push_back(i);
while (mn.front() <= i - K)
mn.pop_front();
while (mx.front() <= i - K)
mx.pop_front();
if (i >= K - 1) {
long long z = s - a[mn.front()] - a[mx.front()];
if (z > best) {
best = z;
pos = i - K + 2;
}
}
}
cout << pos << ' ' << best << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。