309. 买卖股票的最佳时机含冷冻期
1. doc reading
0持有 1未持有 2冷冻 3卖出
持有来自于:
- 原来就持有
- 冻结期刚过,又买入。
- 昨天未持有,又买入。
未持有来自于:
- 昨天就没持有
- 昨天是冷冻期
冷冻期来自于:
- 昨天卖出
卖出来自于:
- 昨天持有。
初始化:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [[0] * 4 for _ in range(len(prices))]
dp[0][0] = -prices[0]
for idx in range(1, len(prices)): # 一定要注意这里是从1开始,因为0行已经初始化。
dp[idx][0] = max(dp[idx - 1][0], dp[idx - 1][1] - prices[idx], dp[idx - 1][2] - prices[idx])
dp[idx][1] = max(dp[idx - 1][1], dp[idx - 1][2])
dp[idx][2] = dp[idx - 1][3]
dp[idx][3] = dp[idx - 1][0] + prices[idx]
# print(dp)
return max(dp[-1][1:])
714. 买卖股票的最佳时机含手续费
1. first idea
三个状态:持有、不持有、卖出
2. doc reading
两个状态:持有、不持有(卖出就交手续费、要不就一直不持有)
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
# 2个状态:持有、不持有: 卖出(交手续费), 本来不持有就不持有
dp = [[0, 0] for _ in range(len(prices))]
dp[0][0] = -prices[0]
for idx in range(1, len(prices)):
dp[idx][0] = max(dp[idx - 1][0], dp[idx - 1][1] - prices[idx])
dp[idx][1] = max(dp[idx - 1][0] + prices[idx] - fee, dp[idx - 1][1])
return dp[-1][1]