CH1201: Maximum Subsequence Sum — Solution
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.
// 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.
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