Best Time to Buy and Sell Stock with Cooldown

medium2-D Dynamic Programmingstate-machine DP (buy/sell/cooldown)Solve on LeetCode#309

Part of Practice: Grids & Two Strings

You are given an array prices where prices[i] is a stock's price on day i. You may complete as many buy-then-sell transactions as you like, but with two rules: you can hold at most one share at a time, and after you sell you must skip the next day entirely (a one-day cooldown) before buying again.

Return the maximum total profit you can earn.

Constraints: 1 <= prices.length <= 5000 and 0 <= prices[i] <= 1000.

Examples

Input:
prices = [1, 2, 3, 0, 2]
Output:
3

Buy at 1, sell at 2 (profit 1), cooldown on day 2, buy at 0, sell at 2 (profit 2). Total 3.

Input:
prices = [1]
Output:
0

With one day there is nothing to trade.

Input:
prices = [2, 1]
Output:
0

Prices only fall, so the best move is to never buy.

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.