Slope Trick — A Convex Function Carried as Two Heaps of Breakpoints

Watch f(x) (a convex piecewise-linear valley) mutate as we relax (prefix-min) and add |x − a| penalties. The left max-heap and right min-heap hold the breakpoints; their tops bound the flat minimum.

add |x−a| : O(log n) prefix-min : O(1) whole DP : O(n log n) space : O(n)
step 0/0
left heap top (left floor) right heap top (right floor) pushing popping / rebalance valley floor (argmin)

f(x) — convex piecewise-linear cost function

Operation log

State

minVal = 0
floor = [—, —]
a_i =

L (max-heap)

R (min-heap)

What is happening

Press Play or Step. Each element a_i triggers a relax (clear R) then add |x − a_i|.

Complexity

OperationCost
add |x − a|O(log n)
one-sided rampO(log n)
prefix-min (clear)O(1) amortized
shift (lazy)O(1)
read minVal / floorO(1)
whole DP (n steps)O(n log n)
memoryO(n) (range-independent)