Back to track
#41 Medium Intermediate

Sliding Window Max

Open the editor

Problem

Find max in each window of size k.

Constraints

1 <= N <= 200000
1 <= k <= N

Hints

  1. 1

    Deque

  2. 2

    Maintain decreasing queue

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#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 (int i = 0; i < n; i++) cin >> a[i];
  deque<int> dq;
  vector<long long> out;
  for (int i = 0; i < n; i++) {
    while (!dq.empty() && dq.front() <= i - k) dq.pop_front();
    while (!dq.empty() && a[dq.back()] <= a[i]) dq.pop_back();
    dq.push_back(i);
    if (i >= k - 1) out.push_back(a[dq.front()]);
  }
  for (int i = 0; i < (int)out.size(); i++) {
    if (i) cout << ' ';
    cout << out[i];
  }
  cout << '\n';
  return 0;
}

© 2026 ChitChat