
LeetCode 309: Best Time To Buy And Sell Stock With Cooldown — Step-by-Step Visual Trace
Medium — Dynamic Programming | Array | State Machine The Problem Find the maximum profit from buying and selling stocks with a cooldown period of one day after each sale. You can complete multiple transactions but must wait one day after selling before buying again. Approach Use dynamic programming with three states: buy (maximum profit after buying), sell (maximum profit after selling), and cooldown (maximum profit during cooldown). Track the optimal profit for each state at every day by considering all possible transitions. Time: O(n) · Space: O(1) Code class Solution : def maxProfit ( self , prices : List [ int ]) -> int : if not prices : return 0 # Initialize variables to represent the maximum profit after each action. buy = - prices [ 0 ] # Maximum profit after buying on day 0 (negative because we spend money). sell = 0 # Maximum profit after selling on day 0 (no profit yet). cooldown = 0 # Maximum profit after cooldown on day 0 (no profit yet). for i in range ( 1 , len ( prices )
Continue reading on Dev.to
Opens in a new tab

