Monotonic Queues in Dynamic Programming
Sliding-window optima that cut DP transitions from O(k) to O(1).
A frog crosses a river on stones, each with a landing cost, and can jump at most stones ahead. The obvious dynamic program tries all previous stones for every stone: . But those candidates form a sliding window, and a window's minimum is exactly what a monotonic deque maintains, so the same program runs in . Bounded knapsack and length-constrained subarray sums fall to the same idea.
What you’ll learn
- Recognize the windowed transition with non-decreasing window ends, and evaluate it in total with a monotonic deque.
- Prove the deque invariant and the amortized bound, and state exactly when the technique applies.
- Apply it to minimum-cost jumps, maximum-sum subarrays with a length in , and the shortest subarray with sum at least when values can be negative.
- Solve bounded knapsack in by splitting the capacities into residue classes.
- Relate the monotone queue to the convex hull trick, Monge-array methods, two-stack window aggregation and fine-grained lower bounds for one-dimensional dynamic programming.
Windowed transitions
Many dynamic programs have the shape
where depends on alone (often , or plus a term in ) and the window ends never move left as grows. Scanning every window costs for windows of length . A sparse table or a segment tree answers any window in or , but these windows slide, and the minimum of a sliding window is what a monotonic deque maintains in amortized time.
from collections import deque
def min_cost_jumps(c, k):
n = len(c)
dp = [0] * n
dp[0] = c[0]
dq = deque([0]) # indices j < i; dp values increase front to back
for i in range(1, n):
if dq[0] < i - k:
dq.popleft() # j = i - k - 1 just left the window [i-k, i-1]
dp[i] = c[i] + dp[dq[0]]
while dq and dp[dq[-1]] >= dp[i]:
dq.pop() # dominated: older and not cheaper
dq.append(i)
return dp[-1]For and , the states are : the best route lands on stones 0, 2, 4, 6 and 8, for . Each index enters the deque once and leaves at most once, so the program takes time instead of .
Keep the same costs but allow only jumps of length . The states begin . What is , the cheapest way to stand on the stone of cost 9?
Show the answer
14
With jumps of at most 2, stone 3 is reachable only from stones 1 and 2, so . With , stone 0 was in the window too, giving .
Why the deque works, and when
Invariant. After the updates for state , the deque holds, in increasing order of index, exactly those indices of the window whose value is smaller than every later value in the window: the window's strict suffix minima.
The front is the minimum. Values strictly increase along the deque, and every window index missing from it is dominated by a later index with a value no larger, so the front holds the window's minimum.
Monotone ends make discarding safe. An index popped from the back is dominated by a later with ; since never decreases, stays in every future window at least as long as would, so is never needed again. An index that falls below never comes back either.
Amortized cost. Every index is appended once and removed at most once, from one end or the other, so by the aggregate method the total work is linear:
Which transition can a single monotonic deque speed up to amortized time per state?
- for arbitrary sets
Show the answer
B.
The window has both ends non-decreasing in , and the value depends on alone: a sliding-window maximum. The other transitions either mix and in the cost, so the candidates' order changes with , or use arbitrary sets with no sliding structure.
Windows over prefix sums
Subarray problems become window problems on prefix sums. With and , the sum of the half-open range , of length , is . To find the maximum sum of a subarray whose length lies in , maximize over the quantity : a sliding-window minimum over the allowed left ends.
from collections import deque
def max_sum_len_between(a, lo, hi):
"""Largest sum of a subarray whose length is in [lo, hi], with 1 <= lo <= hi <= len(a)."""
P = [0]
for x in a:
P.append(P[-1] + x)
best, dq = None, deque() # candidate left ends l; P[l] increases front to back
for r in range(lo, len(a) + 1): # the subarray is a[l .. r-1], of length r - l
l_new = r - lo # this left end has just become allowed
while dq and P[dq[-1]] >= P[l_new]:
dq.pop()
dq.append(l_new)
if dq[0] < r - hi:
dq.popleft() # too far left: the length would exceed hi
s = P[r] - P[dq[0]]
best = s if best is None else max(best, s)
return besttime. On with lengths from 2 to 3, the answer is 10, from . Without the length bounds, Kadane's algorithm solves the problem; with them, the deque keeps it linear.
A second classic is the shortest subarray with sum at least when values may be negative (with positive values only, two pointers suffice). For each right end we want the largest left end with . Keep candidate left ends in a deque with increasing prefix sums, since a later index with a smaller or equal prefix sum is a better left end for every future . For each : first pop from the front while , recording , because a front that works now can only give longer answers later; then pop from the back while , and append . Both ends move only forward, so the total time is .
Bounded knapsack by residue classes
In the bounded knapsack problem, an item type has weight , value and copies. Adding it to a table of best values gives
Done directly, that costs per item type, and splitting the copies into bundles of copies costs . The monotone queue costs . Group the capacities by their residue and write :
a sliding-window maximum over , with windows of length , inside each residue class. The classes cover the capacities once, so each item type costs , and item types cost .
from collections import deque
def bounded_knapsack(items, W):
"""items: (weight, value, count) triples. Best value with total weight <= W."""
dp = [0] * (W + 1)
for w, v, cnt in items:
new = dp[:]
for r in range(w): # residue class r, r + w, r + 2w, ...
dq = deque() # positions s'; keys dp[r+s'w] - s'v decrease
for s, x in enumerate(range(r, W + 1, w)):
key = dp[x] - s * v
while dq and dp[r + dq[-1] * w] - dq[-1] * v <= key:
dq.pop()
dq.append(s)
if dq[0] < s - cnt:
dq.popleft() # would need more than cnt copies
best = dq[0]
new[x] = dp[r + best * w] - best * v + s * v
dp = new
return dp[W]For item types and capacity 13, the best value is 21, for instance with three items of weight 4. The deque stores positions of the residue class with strictly decreasing keys from front to back, and positions more than steps back leave from the front.
Think first Why do the candidates for capacity form a window of positions inside one residue class?
Taking copies moves from capacity to , so the possible sources are : all with the same residue modulo , at most steps back. Inside the class they are the contiguous positions , a window that slides by one as grows, which is exactly what a monotonic deque handles.
Beyond the window: related speedups and limits
The monotone queue is the simplest member of a family of speedups, developed in the Dynamic Programming lesson Speeding Up Dynamic Programming and its Optimal lessons:
- The convex hull trick handles : each is a line, and the minimum over lines at is a lower envelope. With monotone slopes and queries the envelope is again maintained in a deque.
- Knuth's optimization and Monge arrays apply when costs satisfy the quadrangle inequality, so that optimal choices move monotonically. The SMAWK algorithm of Aggarwal, Klawe, Moran, Shor and Wilber (1987) finds all row minima of a totally monotone matrix in time, and Galil and Park (1990) solved concave one-dimensional dynamic programs in linear time.
- Window aggregation without a deque. For an associative operation that is not a minimum or maximum (gcd, matrix products, composed functions), a queue built from two stacks that store running aggregates answers every window with amortized operations. Tangwongsan, Hirzel and Schneider (2017) deamortized it to worst-case operations per update for any associative operator, in the spirit of the real-time queues of the Stacks lessons.
Key takeaways
- A transition with non-decreasing window ends and depending on alone is a sliding-window minimum: a monotonic deque makes the whole program instead of .
- The deque holds the window's strict suffix minima. Monotone window ends make it safe to discard dominated and expired indices, and each index is appended and removed at most once.
- Prefix sums turn length-constrained subarray problems into window problems, and residue classes turn bounded knapsack into sliding windows, in total.
- Costs that mix and need the convex hull trick, Knuth's optimization or SMAWK; aggregates other than minimum and maximum need two-stack aggregation; and one-dimensional DP in general has fine-grained quadratic lower bounds.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why must the window ends and be non-decreasing for the monotonic-deque DP to be correct?
- Otherwise the deque could overflow
- Because the values must arrive in sorted order
- Because an index discarded as dominated or expired must never be needed by a later window
- They need not be: any windows work
Show the answer
C. Because an index discarded as dominated or expired must never be needed by a later window
A dominated index is dropped because a later index is no worse and stays in every future window at least as long; an expired index is dropped because no later window reaches back to it. Both arguments need the window's ends to move only forward.
In the residue-class method for bounded knapsack, why does each item type cost only time?
- Because each of the capacities lies in exactly one residue class, where it enters and leaves a deque at most once
- Because the counts are small
- Because the values are sorted first
- Because binary splitting reduces each count to
Show the answer
A. Because each of the capacities lies in exactly one residue class, where it enters and leaves a deque at most once
The classes for partition the capacities, and within a class each position is appended once and popped at most once, so each item type costs whatever its count .
For which transition is the convex hull trick, rather than a monotonic deque over a window, the natural speedup?
Show the answer
D.
Each contributes the line , and is the lower envelope of these lines at . The candidates' order changes with , so window domination does not apply, but the envelope can be maintained, again with a deque when the slopes and the queries are monotone.
You need the gcd of every window of consecutive numbers. Why can't a monotonic deque do it, and what can?
- It can: keep the deque decreasing in value
- The gcd is not one selected element, so no candidate can be discarded; a two-stack queue with running gcds answers every window with amortized gcd computations
- Nothing faster than gcd computations is possible
- Sort each window and take its first element
Show the answer
B. The gcd is not one selected element, so no candidate can be discarded; a two-stack queue with running gcds answers every window with amortized gcd computations
A deque works for minimum and maximum because a dominated element can never matter again. The gcd depends on all the elements. Two stacks, each entry storing the gcd of itself and everything below it, combine their two tops for each window, and every element moves between the stacks at most once.
Further reading
- CP-Algorithms, "Knapsack Problem": bounded knapsack by binary grouping and by monotone queues.
- A. Aggarwal, M. M. Klawe, S. Moran, P. Shor & R. Wilber, "Geometric applications of a matrix-searching algorithm," Algorithmica 2 (1987), 195–208.
- Z. Galil & K. Park, "A linear-time algorithm for concave one-dimensional dynamic programming," Information Processing Letters (1990).
- M. Künnemann, R. Paturi & S. Schneider, "On the fine-grained complexity of one-dimensional dynamic programming," Proceedings of ICALP (2017).
- K. Tangwongsan, M. Hirzel & S. Schneider, "Low-latency sliding-window aggregation in worst-case constant time," Proceedings of the ACM Conference on Distributed and Event-Based Systems (2017).