---
id: 205
lang: en
translation_of: index.md
source_sha256: 315d1f50cf5f7bdd4ee3bff572775426c18728ed87409c7f16cc9aee89a74efb
title: "CH1201: Maximum Subsequence Sum — Solution"
description: "Using prefix sums and a monotonic queue to drop positions that can never give the best subsequence of length at most m."
tags: ["OI","NOIP","Priority Queue"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The heading “Solve this Problem with the Priority Queue” was written in English in the original and is kept as is, although the body uses a monotonic queue (单调队列); the tag 优先队列 is likewise rendered as Priority Queue per tags.yaml."
  - "“not a big deal.” was written in English in the original and is kept as is."
  - "The inline formula \\(sum[i]>sum[j],其中i<j\\) contains the Chinese word 其中 (“where”) outside any \\text{…}; TeX is kept identical."
---

## Solve this Problem with the Priority Queue

The main goal of a monotonic queue is actually quite similar to the main goal of a monotonic stack: both are about **directly ruling out, in a monotone problem, the answers that can be ruled out, and computing with the rest**.

In this problem, we will use a monotonic queue to solve it. First, we use prefix sums for fast computation. Then, on the basis of the prefix sums, we will use a strategy in this problem, namely: if two positions have prefix sums $sum[i]>sum[j],其中i<j$, then the element at position $i$ is completely useless to us. The reason is that if we want to get the subsequence with the largest sum within length $m$, for an element like this, whose prefix sum is both larger and earlier, the optimal solution is never made up from this element.

Let's use a few code blocks to briefly describe our strategy.

<!--more-->

```cpp
// ll stands for long long
const int maxn = 300200;
ll n, arr[maxn], sum[maxn], m, q[maxn];
```

Declared a few variables, not a big deal.

```cpp
ll l = 1, r = 1, ans = -1e9;
q[1] = 0;
for (int i = 1; i <= n; i++)
{
    while (l <= r && q[l] < i - m)
        l++;
    ans = max(ans, sum[i] - sum[q[l]]);
    while (l <= r && sum[q[r]] >= sum[i])
        r--;
    q[++r] = i;
}
```

We first define the queue head and the queue tail, plus an infinitely small answer. After that, we enumerate the element $i$. In the loop, we first eliminate the elements whose distance exceeds $m$. Then we record the answer. Then it's time to apply our strategy. We eliminate the answers that are not part of the optimal solution. After that, we record the answer at position $++r$ as $i$.

Full code: [https://gist.github.com/kaloronahuang/d58747f88c0d6369d70ffd4d291af221](https://gist.github.com/kaloronahuang/d58747f88c0d6369d70ffd4d291af221)
