Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 865D Buy Low Sell High - The Idea

Retroactive decisions

Use a min-heap to track all previous prices. When you see price pip_i, you have two choices: buy at pip_i or sell shares bought earlier.

If pi>heap.top()p_i > \text{heap.top()}, you can profit by selling. Pop the smallest price from the heap (the buy price), add piheap.top()p_i - \text{heap.top()} to profit. Then push pip_i twice: once as the sell price just used, once as a potential buy for the future. This "undoes" the sell if a better opportunity comes.