Given an aray of size n ≤ 10^6, determine the maximum and minimum values in each sliding window of size k.
Input:
- Two integers n and k representing the array length and window size.
- A line containing n integers representing the array elements.
Output:
- Two lines containing the minimum and maximum values for each sliding window positino.
Example:
Input:
8 3
1 3 -1 -3 5 3 6 7
Output:
-1 -3 -3 -3 3 3
3 3 5 5 6 7
Code:
#include <iostream>
using namespace std;
const int N = 1000010;
int a[N], q[N];
int main() {
int n, k;
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
int hh = 0, tt = -1;
for (int i = 0; i < n; i++) {
if (hh <= tt && i - k + 1 > q[hh]) hh++;
while (hh <= tt && a[q[tt]] >= a[i]) tt--;
q[++tt] = i;
if (i >= k - 1) printf("%d ", a[q[hh]]);
}
puts("");
hh = 0, tt = -1;
for (int i = 0; i < n; i++) {
if (hh <= tt && i - k + 1 > q[hh]) hh++;
while (hh <= tt && a[q[tt]] <= a[i]) tt--;
q[++tt] = i;
if (i >= k - 1) printf("%d ", a[q[hh]]);
}
puts("");
return 0;
}