Example 1
- Input
- prices = [1, 2, 3, 0, 2]
- Output
- 3
Buy day 0, sell day 1 (profit 1), cooldown day 2, buy day 3, sell day 4 (profit 2); total 3.
Each day lists a stock price, you may hold at most one share, and selling forces you to skip buying on the next day. Choose any number of buy and sell days to maximise total profit under that cooldown rule.
You are given an array prices where prices[i] is the price of a stock on day i. You may complete as many transactions as you like, but you must sell before you can buy again, and after selling you enter a one-day cooldown during which buying is forbidden.
Holding at most one share at a time, pick buy and sell days that respect the cooldown and maximise total profit. Doing nothing is always allowed, so the answer is never negative.
Return that maximum achievable profit.
1 <= prices.length <= 50000 <= prices[i] <= 1000Buy day 0, sell day 1 (profit 1), cooldown day 2, buy day 3, sell day 4 (profit 2); total 3.
A single day allows no completed transaction.
Buying at 1 and selling at 2 earns 1 but blocks buying at 0 on the next day. Skip that trade, buy at 0 on day 2 and sell at 2 on day 3 to earn 2. Adding every upward price difference would incorrectly report 3.
Every later selling price is below its buying price, so all completed trades lose money. Taking no trades earns 0 and is optimal.
A sale changes tomorrow's options: being empty-handed after selling is different from being empty-handed after resting. On [1, 2, 3, 0, 2], selling at 3 blocks the attractive buy at 0, while selling earlier at 2 leaves that buy available and earns 3 overall. Keep track of holding, cooling down, and being free to buy; profit alone does not say which actions remain legal.
Reveal Recursive Day Choice: intuition, complexity, and code
prices = [1], where no sale is possible and the answer is 0.prices = [5, 4, 3, 1], where every trade loses and sitting out wins with 0.sold reads an already-updated hold from the same day.When today’s choices restrict tomorrow’s, model each day as a small set of states and roll their best values forward with fixed transition rules.