给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
返回获得利润的最大值。
注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
用动态规划,每天有两种状态,要么持有股票,要么没有持有股票。
f
(
t
,
有
)
f(t,有)
f(t,有)表示在第t天,持有股票时的利润。
f
(
t
,
无
)
f(t,无)
f(t,无)表示在第t天,没有持有股票时的利润。
动态转移方程很好理解:
如果持有股票,可能是昨天没持有股票,今天刚买入,或者昨天就有股票了。
f
(
t
,
有
)
=
max
[
f
(
t
−
1
,
无
)
−
(
p
r
i
c
e
[
t
]
+
f
e
e
)
,
f
(
t
−
1
,
有
)
]
f(t,有) = \max[f(t-1,无)-(price[t]+fee),\ f(t-1,有)]
f(t,有)=max[f(t−1,无)−(price[t]+fee), f(t−1,有)]
如果没有股票,可能是昨天有股票,今天刚卖掉,或者昨天就没有。
f
(
t
,
无
)
=
max
[
f
(
t
−
1
,
有
)
+
p
r
i
c
e
[
t
]
,
f
(
t
−
1
,
无
)
]
f(t,无) = \max[f(t-1,有)+price[t],\ f(t-1,无)]
f(t,无)=max[f(t−1,有)+price[t], f(t−1,无)]
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
days = len(prices)
dp = [[0,0] for _ in range(days)]
dp[0][1] = -prices[0]-fee
for t in range(1,days):
dp[t][1] = max(dp[t-1][0]-prices[t]-fee,dp[t-1][1])
dp[t][0] = max(dp[t-1][1]+prices[t],dp[t-1][0])
return dp[days-1][0]
分析发现,其实第 t t t天的收益只与前一天的状态有关,因此可以优化代码,只用两个变量来储存过去的信息:
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
have,no = -prices[0]-fee,0
for t in range(1,len(prices)):
have,no = max(no-prices[t]-fee,have),max(have+prices[t],no)
return no
虽然Python真的很慢,但是优化以后还是有点提升的orz