Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 865D Buy Low Sell High - Walkthrough

Tracing the greedy insight

Buy and sell stocks, at most one held at a time, unlimited transactions. get the highest profit. Insight: treat each price as an opportunity. Either buy (add to heap), sell (pop min and profit), or hold. Greedy: when seeing price pp, compare to heap min mm.

If p>mp > m, sell (profit pmp - m) and add pp back (can 'regret' and re-buy). Adding pp back allows changing past decisions. This is the 'regret' trick. Total profit is sum of all positive trades.