Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 kk stones ahead. The obvious dynamic program tries all kk previous stones for every stone: O(nk)O(nk). 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 O(n)O(n). Bounded knapsack and length-constrained subarray sums fall to the same idea.

What you’ll learn

  • Recognize the windowed transition dp[i]=c(i)+min⁡L(i)≤j≤R(i)v(j)dp[i] = c(i) + \min_{L(i) \le j \le R(i)} v(j) with non-decreasing window ends, and evaluate it in O(n)O(n) 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 [lo,hi][lo, hi], and the shortest subarray with sum at least KK when values can be negative.
  • Solve bounded knapsack in O(nW)O(nW) 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

dp[i]=c(i)+min⁡L(i) ≤ j ≤ R(i)v(j),dp[i] = c(i) + \min_{L(i) \,\le\, j \,\le\, R(i)} v(j),

where v(j)v(j) depends on jj alone (often v(j)=dp[j]v(j) = dp[j], or dp[j]dp[j] plus a term in jj) and the window ends L(i)≤R(i)L(i) \le R(i) never move left as ii grows. Scanning every window costs O(nk)O(nk) for windows of length kk. A sparse table or a segment tree answers any window in O(1)O(1) or O(log⁡n)O(\log n), but these windows slide, and the minimum of a sliding window is what a monotonic deque maintains in O(1)O(1) amortized time.

python
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 c=[3,7,2,9,4,8,1,6,5]c = [3, 7, 2, 9, 4, 8, 1, 6, 5] and k=3k = 3, the states are dp=[3,10,5,12,9,13,10,15,15]dp = [3, 10, 5, 12, 9, 13, 10, 15, 15]: the best route lands on stones 0, 2, 4, 6 and 8, for 3+2+4+1+5=153 + 2 + 4 + 1 + 5 = 15. Each index enters the deque once and leaves at most once, so the program takes O(n)O(n) time instead of O(nk)O(nk).

Predict before you look

Keep the same costs but allow only jumps of length k=2k = 2. The states begin dp=[3,10,5,… ]dp = [3, 10, 5, \dots]. What is dp[3]dp[3], 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 dp[3]=9+min⁡(10,5)=14dp[3] = 9 + \min(10, 5) = 14. With k=3k = 3, stone 0 was in the window too, giving 9+min⁡(3,10,5)=129 + \min(3, 10, 5) = 12.

Why the deque works, and when

DerivationProof
  1. deque={ j∈[L(i),R(i)]  :  v(j)<v(j′) for all j<j′≤R(i) }\text{deque} = \{\, j \in [L(i), R(i)] \;:\; v(j) < v(j') \text{ for all } j < j' \le R(i) \,\}

    Invariant. After the updates for state ii, the deque holds, in increasing order of index, exactly those indices jj of the window whose value is smaller than every later value in the window: the window's strict suffix minima.

  2. v(front)=min⁡L(i)≤j≤R(i)v(j)v(\text{front}) = \min_{L(i) \le j \le R(i)} v(j)

    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.

  3. L(i)≤L(i+1),R(i)≤R(i+1)L(i) \le L(i + 1), \qquad R(i) \le R(i + 1)

    Monotone ends make discarding safe. An index j′j' popped from the back is dominated by a later jj with v(j)≤v(j′)v(j) \le v(j'); since LL never decreases, jj stays in every future window at least as long as j′j' would, so j′j' is never needed again. An index that falls below L(i)L(i) never comes back either.

  4. #appends+#removals ≤ 2N\#\text{appends} + \#\text{removals} \ \le\ 2N

    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:

Check your understanding

Which transition can a single monotonic deque speed up to O(1)O(1) amortized time per state?

  1. dp[i]=min⁡0≤j<i(dp[j]+(xi−xj)2)dp[i] = \min_{0 \le j < i} \big(dp[j] + (x_i - x_j)^2\big)
  2. dp[i]=a[i]+max⁡i−k≤j≤i−2dp[j]dp[i] = a[i] + \max_{i - k \le j \le i - 2} dp[j]
  3. dp[i]=min⁡j∈Sidp[j]dp[i] = \min_{j \in S_i} dp[j] for arbitrary sets SiS_i
  4. dp[i]=min⁡0≤j<i(dp[j]+bj⋅xi)dp[i] = \min_{0 \le j < i} \big(dp[j] + b_j \cdot x_i\big)
Show the answer

B. dp[i]=a[i]+max⁡i−k≤j≤i−2dp[j]dp[i] = a[i] + \max_{i - k \le j \le i - 2} dp[j]

The window [i−k,i−2][i - k, i - 2] has both ends non-decreasing in ii, and the value dp[j]dp[j] depends on jj alone: a sliding-window maximum. The other transitions either mix ii and jj in the cost, so the candidates' order changes with ii, or use arbitrary sets with no sliding structure.

Windows over prefix sums

Subarray problems become window problems on prefix sums. With P[0]=0P[0] = 0 and P[i+1]=P[i]+a[i]P[i+1] = P[i] + a[i], the sum of the half-open range a[l..r)a[l..r), of length r−lr - l, is P[r]−P[l]P[r] - P[l]. To find the maximum sum of a subarray whose length lies in [lo,hi][lo, hi], maximize over rr the quantity P[r]−min⁡{P[l]:r−hi≤l≤r−lo}P[r] - \min\{P[l] : r - hi \le l \le r - lo\}: a sliding-window minimum over the allowed left ends.

python
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 best

O(n)O(n) time. On [4,−6,3,5,−2,7,−8,2][4, -6, 3, 5, -2, 7, -8, 2] with lengths from 2 to 3, the answer is 10, from [5,−2,7][5, -2, 7]. 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 KK when values may be negative (with positive values only, two pointers suffice). For each right end rr we want the largest left end ll with P[l]≤P[r]−KP[l] \le P[r] - K. 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 rr. For each rr: first pop from the front while P[r]−P[front]≥KP[r] - P[\text{front}] \ge K, recording r−frontr - \text{front}, because a front that works now can only give longer answers later; then pop from the back while P[back]≥P[r]P[\text{back}] \ge P[r], and append rr. Both ends move only forward, so the total time is O(n)O(n).

Bounded knapsack by residue classes

In the bounded knapsack problem, an item type has weight ww, value vv and cc copies. Adding it to a table dp[0..W]dp[0..W] of best values gives

dp′[x]=max⁡0≤q≤c(dp[x−q w]+q v).dp'[x] = \max_{0 \le q \le c} \big(dp[x - q\,w] + q\,v\big).

Done directly, that costs O(Wc)O(Wc) per item type, and splitting the cc copies into bundles of 1,2,4,…1, 2, 4, \dots copies costs O(Wlog⁡c)O(W \log c). The monotone queue costs O(W)O(W). Group the capacities by their residue r=x mod wr = x \bmod w and write x=r+s wx = r + s\,w:

dp′[r+s w]=s v+max⁡s−c ≤ s′ ≤ s(dp[r+s′ w]−s′ v),dp'[r + s\,w] = s\,v + \max_{s - c \,\le\, s' \,\le\, s} \big(dp[r + s'\,w] - s'\,v\big),

a sliding-window maximum over s′s', with windows of length c+1c + 1, inside each residue class. The classes cover the W+1W + 1 capacities once, so each item type costs O(W)O(W), and nn item types cost O(nW)O(nW).

python
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 (w,v,c)=(3,5,2),(4,7,3),(2,2,4)(w, v, c) = (3, 5, 2), (4, 7, 3), (2, 2, 4) and capacity 13, the best value is 21, for instance with three items of weight 4. The deque stores positions s′s' of the residue class with strictly decreasing keys from front to back, and positions more than cc steps back leave from the front.

Think first Why do the candidates for capacity x=r+s wx = r + s\,w form a window of positions s−c,…,ss - c, \dots, s inside one residue class?

Taking qq copies moves from capacity x−q wx - q\,w to xx, so the possible sources are x,x−w,…,x−c wx, x - w, \dots, x - c\,w: all with the same residue modulo ww, at most cc steps back. Inside the class they are the contiguous positions s−c..ss - c..s, a window that slides by one as ss 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 dp[i]=min⁡j(dp[j]+bj xi)dp[i] = \min_j (dp[j] + b_j\, x_i): each jj is a line, and the minimum over lines at xix_i 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 n×nn \times n matrix in O(n)O(n) 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 O(1)O(1) amortized operations. Tangwongsan, Hirzel and Schneider (2017) deamortized it to O(1)O(1) 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 dp[i]=c(i)+min⁡L(i)≤j≤R(i)v(j)dp[i] = c(i) + \min_{L(i) \le j \le R(i)} v(j) with non-decreasing window ends and vv depending on jj alone is a sliding-window minimum: a monotonic deque makes the whole program O(n)O(n) instead of O(nk)O(nk).
  • 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, O(nW)O(nW) in total.
  • Costs that mix ii and jj 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.

Question 1

Why must the window ends L(i)L(i) and R(i)R(i) be non-decreasing for the monotonic-deque DP to be correct?

  1. Otherwise the deque could overflow
  2. Because the values v(j)v(j) must arrive in sorted order
  3. Because an index discarded as dominated or expired must never be needed by a later window
  4. 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 j′j' is dropped because a later index jj 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.

Question 2

In the residue-class method for bounded knapsack, why does each item type cost only O(W)O(W) time?

  1. Because each of the W+1W + 1 capacities lies in exactly one residue class, where it enters and leaves a deque at most once
  2. Because the counts cc are small
  3. Because the values are sorted first
  4. Because binary splitting reduces each count to log⁡c\log c
Show the answer

A. Because each of the W+1W + 1 capacities lies in exactly one residue class, where it enters and leaves a deque at most once

The classes r,r+w,r+2w,…r, r + w, r + 2w, \dots for r=0,…,w−1r = 0, \dots, w - 1 partition the capacities, and within a class each position is appended once and popped at most once, so each item type costs O(W)O(W) whatever its count cc.

Question 3

For which transition is the convex hull trick, rather than a monotonic deque over a window, the natural speedup?

  1. dp[i]=ci+min⁡i−k≤j<idp[j]dp[i] = c_i + \min_{i - k \le j < i} dp[j]
  2. dp[i]=ai+max⁡i−k≤j<idp[j]dp[i] = a_i + \max_{i - k \le j < i} dp[j]
  3. dp[i]=dp[i−1]+aidp[i] = dp[i - 1] + a_i
  4. dp[i]=min⁡j<i(dp[j]+bj⋅xi)dp[i] = \min_{j < i} \big(dp[j] + b_j \cdot x_i\big)
Show the answer

D. dp[i]=min⁡j<i(dp[j]+bj⋅xi)dp[i] = \min_{j < i} \big(dp[j] + b_j \cdot x_i\big)

Each jj contributes the line y=bj x+dp[j]y = b_j\, x + dp[j], and dp[i]dp[i] is the lower envelope of these lines at xix_i. The candidates' order changes with ii, so window domination does not apply, but the envelope can be maintained, again with a deque when the slopes and the queries are monotone.

Question 4

You need the gcd of every window of kk consecutive numbers. Why can't a monotonic deque do it, and what can?

  1. It can: keep the deque decreasing in value
  2. The gcd is not one selected element, so no candidate can be discarded; a two-stack queue with running gcds answers every window with O(1)O(1) amortized gcd computations
  3. Nothing faster than O(nk)O(nk) gcd computations is possible
  4. 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 O(1)O(1) 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).