Skip to content

Best Time to Buy and Sell Stock with Cooldown

MediumDynamic Programming
Decode it first. Clues, constraints, pattern and plan before any code.

prices[i] is a stock's price on day i. You may make as many transactions as you like (buy one share, then sell it), with two rules: you can hold at most one share at a time, and after you sell you must wait one day (a one-day cooldown) before buying again. Return the maximum profit.

prices = [1, 2, 3, 0, 2]  →  3   (buy 1, sell 2, cooldown, buy 0, sell 2)
prices = [1]              →  0

Constraints

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000