题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
难度:中等
描述:
给定一个整数数组prices
,其中第 prices[i]
表示第 _i_
天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
- 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
提示:prices.length: [1, 5000]
题解
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
# r[i]代表第i天结束后的最大利润,有三种状态
# 0:持有股票
# 1:未持有股票,未在冷冻期
# 2:未持有股票,处于冷冻期
r = [[0] * 3 for _ in range(n)]
r[0][0] = -prices[0]
for i in range(1, n):
r[i][0] = max(r[i-1][0], r[i-1][1] - prices[i])
r[i][1] = max(r[i-1][1], r[i-1][2])
r[i][2] = r[i-1][0] + prices[i]
return max(r[n-1][1], r[n-1][2])