Best Time to Buy and Sell Stock with Cooldown
Problem: Best Time to Buy and Sell Stock with Cooldown
The difference between this problem with the easiest buy and sell stock is that there's a cooldown, which means every time we buy stock we can only refer to the result of 2 periods before.
Code in Python:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
dp = [[0-prices[0]], [0]]
for i in xrange(1, len(prices)):
buy = dp[1][i-2] - prices[i] if i > 1 else 0-prices[i]
sell = dp[0][-1] + prices[i]
dp[0].append(max(buy, dp[0][-1]))
dp[1].append(max(sell, dp[1][-1]))
return max(dp[1][-1], 0)