滑动窗口最值(单调队列)

时间:2022-05-04 17:39:09

问题:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
解法:利用单调队列来保存未过期(在w窗口内)的之前的最大值,如果当前值大于该值,就从队首弹出,直到找到大于当前值得位置,将当前值的位置压入队首,如果数据过期,就从队尾删除。(单调队列)

int a[maxn];
int n;
int w;
deque<int> q;
void solve() {
for (int i = 0; i<n; i++) {
while (!q.empty()&&a[i] >= a[q.front()]) q.pop_front();
q.push_front(i);
if (a[i] < a[q.front()]) q.push_front(i);
if (i - q.back() == w) q.pop_back();
if (i >= w - 1) cout << a[q.back()] << endl;
}
}