Dynamic Programming21 sections · 916 units
Open in Course

CSES - Heap Mechanics

Maintaining breakpoints

Process elements left-to-right. For each aia_i, push it to the max-heap. If ai<heap.top()a_i < \text{heap.top()}, the array violates non-decreasing.

Pop the largest previous value, pay the cost heap.top()ai\text{heap.top()} - a_i, then push aia_i again. The double-push maintains the correct number of slope-change points. Why does this work? The heap represents the piecewise linear function. Popping and pushing adjust the slope at aia_i without computing all values.