> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/algorithm-techniques/monotonic.md).

# 单调栈与单调队列

### 单调栈

栈内元素保持单调，常用于求“**下一个更大 / 更小元素**”。

```cpp
// 每个元素右边第一个比它大的位置
stack<int> st;   // 存下标
for (int i = 0; i < n; i++) {
    while (!st.empty() && a[st.top()] < a[i]) {
        ans[st.top()] = i;
        st.pop();
    }
    st.push(i);
}
```

### 单调队列（滑动窗口最值）

用双端队列维护窗口内单调序列，求**定长窗口最大/最小值**，O(n)。

```cpp
deque<int> dq;
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) ans[i] = a[dq.front()];   // 窗口最小值
}
```

### 应用

下一个更大元素、柱状图最大矩形（单调栈）；滑动窗口最值（单调队列）；优化 DP 转移。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/algorithm-techniques/monotonic.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
