#include <iostream>
#include <cstring>
#include <algorithm>
const int N = 1e6 + 10;
int a[N], q[N];
using namespace std;
// 单调队列,存的是数组的值的索引,h = 0, t = -1
//数组的有效索引从1开始
int main(){
int n, k;
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; i ++ ){
scanf("%d", &a[i]);
}
int h = 0, t = -1;
for (int i = 1; i <= n; i ++ ){
//如果队列头的值(即数组的下标)小于i - k + 1,就将队列头移除队列
//即队头什么时候出队列
if(h <= t && q[h] < i - k + 1) h ++;
//如果数组当前元素的值,大于等于数组的索引是队列尾的数组的值,就把队列尾出队
while (h <= t && a[i] <= a[q[t]]) t --;
//把当前值的索引加入队列尾
q[++t] = i;
//如果队列的元素的个数大于等于k,就打印
if(i > k - 1) printf("%d ",a[q[h]]);
}
cout << endl;
//单调队列,h是队列的头索引,t是队列的尾索引
h = 0, t = -1;
for (int i = 1; i <= n; i ++ ){
//如果队列头的值(即数组的下标)小于i - k + 1,就将队列头移除队列
//即队头什么时候出队列
if(h <= t && q[h] < i - k + 1) h ++;
//如果数组当前元素的值,大于等于数组的索引是队列尾的数组的值,就把队列尾出队
while (h <= t && a[i] >= a[q[t]]) t --;
//把当前值的索引加入队列尾
q[++t] = i;
//如果队列的元素的个数大于等于k,就打印
if(i > k - 1) printf("%d ",a[q[h]]);
}
}
06-11
151
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-13
182
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-26
433
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-01
712
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-02
1306
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)