Best Time to Buy and Sell Stock with Cooldown
Description
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Solutions
Let stock[i + 1]
be the maximum profit at day i
holding stock. Let money[i + 1]
be the maximum profit at day i
without holding stock. (days start from 0).
To have stock at day i
, we can either:
have stock at day
i-1
, then the profit isstock[i]
; orbuy stock at day
i
, then we must not sell at dayi-1
. The profit ismoney[i-1] - prices[i]
.Thus,
stock[i + 1] = max(stock[i], money[i - 1] - prices[i])
.
To not have stock at day i
, we can either:
don't have stock at day
i-1
and don't buy at dayi
, then the profit ismoney[i-1]
; orhave stock at day
i-1
and sell the stock at dayi.
Then the profit isstock[i-1] + prices[i]
.Thus,
money[i + 1] = max(stock[i] + prices[i], money[i])
.
money[i]
always larger than stock[i]
, so we return money[n]
.
Optimization
We can optimize to algorithm to use constant space.
Last updated