力扣题目链接
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
示例:
这个问题的特别之处在于引入了一个“冷冻期”的概念,即在卖出股票的次日,不能进行股票的买入。
动态规划是解决这个问题的一个有效方法。考虑到冷冻期的存在,我们需要维护三个状态:
持有股票(hold):
hold[i] = max(hold[i-1], no_hold[i-1] - prices[i])
不持有股票,处于冷冻期(freeze):
freeze[i] = hold[i-1] + prices[i]
不持有股票,不处于冷冻期(no_hold):
no_hold[i] = max(no_hold[i-1], freeze[i-1])
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
hold, freeze, no_hold = [0] * n, [0] * n, [0] * n
hold[0] = -prices[0]
for i in range(1, n):
hold[i] = max(hold[i-1], no_hold[i-1] - prices[i])
freeze[i] = hold[i-1] + prices[i]
no_hold[i] = max(no_hold[i-1], freeze[i-1])
return max(freeze[n-1], no_hold[n-1])
力扣题目链接
给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
示例 1:
解释: 能够达到的最大利润:
注意:
状态定义:
hold[i]
:表示第 i
天结束时持有股票的最大利润。cash[i]
:表示第 i
天结束时不持有股票的最大利润。状态转移:
hold[i]
= max(hold[i-1], cash[i-1] - prices[i])
:表示第 i
天持有股票的最大利润是由前一天持有股票和前一天不持有但在今天买入股票中的较大者决定的。cash[i]
= max(cash[i-1], hold[i-1] + prices[i] - fee)
:表示第 i
天不持有股票的最大利润是由前一天不持有股票和前一天持有但在今天卖出股票(扣除手续费)中的较大者决定的。初始化:
hold[0]
= -prices[0]
:第一天买入股票的情况。cash[0]
= 0
:第一天不持有股票的情况。计算最终结果:
cash[n-1]
,即在最后一天不持有股票的最大利润。class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
if n == 0:
return 0
hold = [0] * n
cash = [0] * n
hold[0] = -prices[0]
for i in range(1, n):
hold[i] = max(hold[i - 1], cash[i - 1] - prices[i])
cash[i] = max(cash[i - 1], hold[i - 1] + prices[i] - fee)
return cash[n - 1]