Stock buy and sell
Stock problems track a small state each day: holding a share or not, and how many transactions are left. Each day you either keep your state or buy (pay the price) or sell (receive it). With unlimited transactions the answer is all the rises; with k transactions keep buy[t] and sell[t] for each t.
How to recognise it
- Prices over days, and buy and sell decisions.
- A limit on the number of transactions, a fee, or a cooldown.
- Holding at most one share at a time.
Holding or not
hold = -infinity; free = 0
each day p:
hold = max(hold, free - p) # keep holding, or buy today
free = max(free, hold + p) # keep waiting, or sell today
| Problem | State |
|---|---|
| one transaction | lowest price so far |
| unlimited | sum of every rise (or hold / free) |
| with a fee | hold / free, subtract the fee on selling |
| at most 2 | buy1, sell1, buy2, sell2 |
| at most k | buy[t], sell[t] for t = 1..k |
Common mistakes
- Selling before buying on the same day in the formulas (update in the right order).
- Starting
holdat 0 instead of minus infinity.
Problems
- Best Time to Buy and Sell Stockeasyguide ready
- Best Time to Buy and Sell Stock IImediumguide ready
- Best Time to Buy and Sell Stock with Transaction Feemediumguide ready
- Best Time to Buy and Sell Stock IIIhardguide ready
- Best Time to Buy and Sell Stock IVhardguide ready