Skip to main content

Best Time to Buy and Sell Stock with Cooldown

Question

Given a list of prices for a stock over a set number of days, what is the maximum profit that can be obtained by buying and selling the stock exactly once, with a cooldown period between the buy and sell transactions?

Example 1
Input: [1,2,3,0,2]
Output: 3 (Buy at 1, sell at 3, cooldown at 0, buy at 0, sell at 2)

Solution

all//Best Time to Buy and Sell Stock with Cooldown.py


# Dynamic programming solution

def maxProfit(prices):

# if prices array is empty, return 0
if not prices:
return 0

# create an array to store the maximum profit,
# starting with 0 at the beginning
max_profit = [0] * len(prices)

# calculate the maximum profit for each day
for i in range(1, len(prices)):

# if today's price is lower than yesterday's price
if prices[i] < prices[i-1]:

# max profit on day i is max profit from yesterday
max_profit[i] = max_profit[i-1]

# if today's price is higher than yesterday's price
else:

# max profit on day i is either max profit from yesterday or
# maximum profit from two days ago plus today's price minus two days ago's price
max_profit[i] = max(max_profit[i-1], max_profit[i-2] + prices[i] - prices[i-2])

# return the maximum profit from the last day
return max_profit[-1]