- Best Time to Buy and Sell Stock with Cooldown
- 难度:Medium| 中等
- 相关知识点:Array Dynamic Programming greedy
- 题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [1,2,3,0,2] Output: 3 Explanation: transactions = [buy, sell, cooldown, buy, sell] Example 2:
Input: prices = [1] Output: 0
Constraints:
1 <= prices.length <= 5000 0 <= prices[i] <= 1000
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
今天卖出了 : dp[i][0] = max(dp[i-1][2], dp[i-1][3]) + price[i] dp[0][0]=0
冷冻期: dp[i][1] = max(dp[i-1][0], dp[i-1][1]) dp[0][1]=0
买入持股:dp[i][2] = dp[i-1][1] - price[i] dp[0][0]=-price[0]
持股没操作:dp[i][3] = max(dp[i-1][2], dp[i-1][3]) dp[0][3]=0
"""
dp=[[0]*4 for i in range(len(prices))]
dp[0][0]=0
dp[0][1]=0
dp[0][2]=-prices[0]
dp[0][3]=-prices[0]
for i in range(1, len(prices)):
dp[i][0] = max(dp[i-1][2], dp[i-1][3]) + prices[i]
dp[i][1] = max(dp[i-1][0], dp[i-1][1])
dp[i][2] = dp[i-1][1] - prices[i]
dp[i][3] = max(dp[i-1][2], dp[i-1][3])
return max(dp[-1])
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
n = len(prices)
buy = [0] * n
sell = [0] * n
cooldown = [0] * n
buy[0] = -prices[0]
for i in range(1, n):
cooldown[i] = sell[i-1]
buy[i] = max(cooldown[i-1]-prices[i], buy[i-1])
sell[i] = max(buy[i-1]+prices[i], sell[i-1])
return max(sell[n-1], cooldown[n-1])
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
n = len(prices)
buy = [0] * n
sell = [0] * n
cooldown = [0] * n
buy[0] = -prices[0]
for i in range(1, n):
cooldown[i] = sell[i-1]
buy[i] = max(cooldown[i-1]-prices[i], buy[i-1])
sell[i] = max(buy[i-1]+prices[i], sell[i-1])
return max(sell[n-1], cooldown[n-1])