Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 865D Buy Low Sell High - Why It Works

Slope function analog

Think of profit as a function of the last action. Each buy/sell pair contributes to the piecewise linear profit function. The heap tracks slope-change points. Pushing pip_i twice after a sell lets you retroactively change the decision. If a higher price appears later, the second pip_i can be popped as a "buy" price.

This is Slope Trick in disguise: you're maintaining a convex function of decisions without storing all states. The heap gives you O(logn)O(\log n) updates.