#309
Best Time to Buy and Sell Stock with Cooldown
medium· 2-D DPruns: 0You are given an array prices where prices[i] is the price of a stock on the ith day. Find the maximum profit you can achieve with these restrictions: you may complete as many transactions as you like (buy one and sell one share at a time), but you may not engage in multiple transactions simultaneously (you must sell before you buy again). After you sell, you cannot buy on the next day (cooldown of one day).
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 404
class Solution:
def maxProfit(self, prices: list[int]) -> int:
hold = -prices[0]
sold = 0
rest = 0
for i in range(1, len(prices)):
prev_hold, prev_sold, prev_rest = hold, sold, rest
hold = max(prev_hold, prev_rest - prices[i])
sold = prev_hold + prices[i]
rest = max(prev_rest, prev_sold)
return max(sold, rest)
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.