---
id: 412
lang: en
translation_of: index.md
source_sha256: d3629fa562500e56b4745c2fcac6a85ffafe22830042cc5cb1274ffa9e28d32c
title: "Optimizing Dynamic Programming with a Monotonic Queue"
description: "At this point we can use a monotonic queue to optimize, and the time complexity can be further reduced to O(n^2) or O(nm)."
tags: ["Dynamic Programming","OI","DP","Monotonic Queue","DP Optimization"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "学习以下 (sic) read as 学习一下, “go learn (them)”."
  - "Link text CH1201:最大子序和题解 rendered with the English title of that post's own translation, “CH1201: Maximum Subsequence Sum — Solution”."
  - "A period was added after the Fence - POJ link, where the Chinese runs straight into the next sentence."
---

## Introduction

Sometimes, when we're working through problems day to day, we run into <span class="slang" data-zh="毒瘤" data-gloss="dúliú, “tumor”. A problem (or problem setter) that is painfully hard, tedious, or full of traps.">nasty</span> DP problems like these. They generally have the following traits:

- Multi-dimensional dynamic programming
- Many nested loops, so they can't get AC on the extreme-case data.
- They usually show up in interval DP, and the brute-force algorithm's complexity is generally $O(n^3)$.

At this point we can use a monotonic queue to optimize, and the time complexity can be further reduced to $O(n^2)$ or $O(nm)$. If any of you don't know monotonic queues, you can go learn them, and while you're at it you can take a look at this post: [CH1201: Maximum Subsequence Sum — Solution](../205-ch1201-max-subsequence-sum/index.en.html)

## Overall on this optimization technique

Let's look at an example problem: [Fence - POJ](http://poj.org/problem?id=1821). This problem is a fairly simple classic DP. Define the state $dp[i][j]$ to mean that the first $i$ people have taken care of the first $j$ units of the wall. Write out the equation:

$$
dp[i][j] = min_{S_i - l_i \leq k < S_i}\{dp[i-1][k]+profit_i*(j-k)\}
$$

This way, the complexity of the whole algorithm is $O(n^3)$. Can we bring it down to $O(n^2)$? We can rearrange the whole equation a bit, and afterwards it looks like this:

$$
dp[i][j] = min_{S_i - l_i \leq k < S_i}\{dp[i-1][k]-profit_i*k\}+profit_i*j
$$

We notice that this way, under the loop over $i$, the whole equation is more or less only tied up with the variable $k$. We find that as long as $k_1<k_2$ and $dp[i-1][k_1]-profit_i*k_1<dp[i-1][k_2]-profit_i*k_2$, we can directly rule out the answer $k_1$. So we can use a monotonic queue to do exactly that.

Below is the core DP code:

```cpp
int calc(int i, int k)
{
    return dp[i - 1][k] - wks[i].p * k;
}

// in ( int main() )
for (int i = 1; i <= k; i++)
{
    deque<int> q;
    for (int j = max(0, wks[i].s - wks[i].l); j <= wks[i].s - 1; j++)
    {
        while (!q.empty() && calc(i, q.back()) <= calc(i, j))
            q.pop_back();
        q.push_back(j);
    }
    for (int j = 1; j <= n; j++)
    {
        dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        if (j >= wks[i].s)
        {
            while (!q.empty() && q.front() < j - wks[i].l)
                q.pop_front();
            if (!q.empty())
                dp[i][j] = max(dp[i][j], calc(i, q.front()) + wks[i].p * j);
        }
    }
}
```

## In Conclusion

This whole monotonic queue optimization lays the groundwork for the slope optimization later on (because the reason I learned this monotonic queue optimization was that a problem required slope optimization), so please make sure you really get this technique.
