Video failed to load

Slope Trick Through Isotonic Regression: Why the Heap Contains Two Copies

554 words
3 minutes
Slope Trick Through Isotonic Regression: Why the Heap Contains Two Copies

Slope trick compresses a convex piecewise-linear DP by storing where its derivative changes. Instead of presenting a general data structure first, we will derive a compact algorithm for a constrained fitting problem.

Given observations a1,…,ana_1,\ldots,a_n, choose real values b1≤⋯≤bnb_1\le\cdots\le b_n minimizing ∑i∣ai−bi∣\sum_i|a_i-b_i|. This is isotonic regression with absolute loss. The observations need not be sorted, and sorting them would change the problem.

The DP function and its shape#

Let Fi(x)F_i(x) be the minimum cost for the first ii observations when the final chosen value is exactly xx. Then

Fi(x)=∣x−ai∣+min⁡y≤xFi−1(y).F_i(x)=|x-a_i|+\min_{y\le x}F_{i-1}(y).

The prefix minimum of a convex function preserves its decreasing portion and flattens everything after a minimum. Adding an absolute value preserves convexity and introduces two units of derivative change at aia_i.

For this recurrence it is convenient to store the prefix minimum Hi(x)=min⁡y≤xFi(y)H_i(x)=\min_{y\le x}F_i(y). Its slope is never positive. Represent it using a constant minimum and left-facing hinges:

Hi(x)=mi+∑ℓ∈Li(ℓ−x)+.H_i(x)=m_i+\sum_{\ell\in L_i}(\ell-x)_+.

Here (z)+=max⁡(z,0)(z)_+=\max(z,0). The multiset LiL_i fits in a max heap. Its largest breakpoint is the left edge of the flat minimum region.

Derive the heap update#

Adding ∣x−a∣|x-a| and taking another prefix minimum yields a compact rule: insert aa twice, remove the largest breakpoint tt, and increase the minimum by t−at-a. Since one inserted value is aa, this increase is nonnegative.

Equivalently, insert aa once; if the heap maximum exceeds aa, replace that maximum by another copy of aa and pay the difference. This second version avoids an unnecessary push and pop when no violation occurs.

long long cost = 0;
std::priority_queue<long long> heap;
for (long long a : observations) {
heap.push(a);
if (heap.top() > a) {
cost += heap.top() - a;
heap.pop();
heap.push(a);
}
}

Why not merely keep one copy of each observation? The heap stores derivative breakpoints, not the original data. A descending pair may force two earlier constraints to share the same breakpoint. Treating it as a set, or deleting duplicates, destroys that information.

trace and exact small-state comparison#

For observations [5,1,4,2][5,1,4,2], the prefix optimum costs are 0,4,4,60,4,4,6. One optimal fit is [1,1,2,2][1,1,2,2]. Another is [2,2,2,2][2,2,2,2]. The optimum need not be unique.

The lab plots the exact DP for integer endpoints on this small instance. Because observations are integers, an integer optimum exists. It runs the direct recurrence, not the heap algorithm, so it is useful as an independent explanation and check.

For observations [5, 1, 4, 2], optimal prefix costs are [0, 4, 4, 6]. Enable JavaScript to inspect endpoint costs.

Beyond this one recurrence#

A full slope-trick structure keeps left and right breakpoint heaps, plus the minimum. Prefix minimization discards the right-facing hinges; suffix minimization discards the left-facing ones. Shifting a function translates its breakpoints. A sliding minimum can often be represented with separate lazy offsets for the heaps.

These extensions solve movement-constrained convex DPs, but they need their own derivations. The single-heap code above does not solve every problem containing absolute values. In particular, weighted observations introduce slope jumps larger than one and may require multiplicity counts rather than literally inserting a breakpoint billions of times.

The algorithm uses O(nlog⁡n)O(n\log n) time and O(n)O(n) storage. long long is needed for accumulated cost, and coordinate differences must also fit its range. The companion isotonic_cost is checked against exhaustive small endpoint DPs on randomized inputs.

Exercise. Require bi+1≥bi+db_{i+1}\ge b_i+d for a fixed integer dd. Transform bib_i and aia_i to remove the gap requirement. Prove that the absolute losses are preserved, then reuse the same heap without changing its internals.

Support & Share

If this article helped you, please share or support!

Sponsor
Slope Trick Through Isotonic Regression: Why the Heap Contains Two Copies
https://blog.wsh.moe/posts/slope-trick-isotonic/
Author
Wsh
Published at
2026-10-24

Comments

LEAVE A NOTE

Join the conversation

Markdown supported

Be kind. Good conversations start with you.

Conversation

Loading conversation…

Comments powered by Waline

Profile Image of the Author
Wsh
Nice to meet you! Hello, I'm Wsh.
Announcement
Any news or updates will be shared here, so check back anytime! Thanks for stopping by, meow >.<
Categories
Tags
Site Statistics
Posts
27
Categories
7
Tags
69
Total Words
124,615
Running Days
0 days
Last Activity
0 days ago
Site Info
Build Platform
Vercel
Blog Version
Firefly v6.16.8
License
CC BY-NC-SA 4.0
Table of Contents