> 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/advanced-dp/rolling-array.md).

# 滚动数组优化

### 为什么需要

二维 DP 若每层只依赖上一层，可把二维数组压成一维，空间从 O(n²) 降到 O(n)。

### 例子：01 背包

```cpp
for (int i = 1; i <= n; i++)
    for (int j = C; j >= w[i]; j--)          // 逆序！
        dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
```

### 顺序方向

| 问题    | 内层顺序 | 原因     |
| ----- | ---- | ------ |
| 01 背包 | 逆序   | 每件只用一次 |
| 完全背包  | 正序   | 每件可用多次 |

### 例子：二维 DP 滚动

```cpp
for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
        f[j] = max(f[j], f[j-1]) + a[i][j];   // 只保留一行
```

### 注意

滚动数组要求状态转移只依赖有限的前几层。若依赖多个历史状态，可保留若干行（如双缓冲）。


---

# 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/advanced-dp/rolling-array.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.
