Tommy Chen home

Monotonic Queue

17 Aug 2025

1. Introduction

2. Implementation

Template: Luogu P1886

For a sequence of length n, a window of length k moves from left to right one position at a time. Find the maximum and minimum in the window after every move.


input
8  3
1  3  -1  -3  5  3  6  7


output
min -1 -3 -3 -3  3  3
max  3  3  5  5  6  7

Approach:


for(int i = 1; i <= n; i++) { // 求最大值
		while(!q.empty() && q.front() < i - k + 1)
			q.pop_front();
		while(!q.empty() && a[q.back()] < a[i])
			q.pop_back();
		q.push_back(i);
  	maxi[i] = a[q.front()];
}


for(int i = 1; i <= n; i++) { // 求最小值
		while(!q.empty() && q.front() < i - k + 1)
			q.pop_front();
		while(!q.empty() && a[q.back()] > a[i])
			q.pop_back();
		q.push_back(i);
		mini[i] = a[q.front()];
}

3. Variations

Example 1: Luogu P1714, maximum subarray sum with a length limit m.

Task: Given a sequence p1, …, pn, find a subarray [l, r] with r − l + 1 ≤ m that maximizes Σi = lr pi. Unlike the template, this problem asks for a sum rather than an extremum, so use prefix sums.

After preprocessing prefix sums in sum[], the sum on [l,r] is sum[r]-sum[l-1].

Approach:

Example 2: Luogu P2216 (two-dimensional).

Task:

Given an a×b integer matrix, find an n×n square in which the difference between the maximum and minimum values is minimal.


input
a = 5, b = 4, n = 2
1   2   5   6
0   17  16  0
16  17  2   1
2   10  2   1
1   2   2   2


output
1

Approach:

Total visits to this site: times