Leetcode 每日一题
题目链接: 714. 买卖股票的最佳时机含手续费
难度: 中等
解题思路: 某一天有持有或者不持有股票两种状态。写出如下状态转移方程。dp[i][0]表示第i天不持有股票,dp[i][1]持有股票。
d
p
[
i
]
[
0
]
=
m
a
x
(
d
p
[
i
−
1
]
[
0
]
,
d
p
[
i
−
1
]
[
1
]
+
p
r
i
c
e
s
[
i
]
−
f
e
e
)
;
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] +prices[i] - fee);
dp[i][0]=max(dp[i−1][0],dp[i−1][1]+prices[i]−fee);
d
p
[
i
]
[
1
]
=
m
a
x
(
d
p
[
i
−
1
]
[
0
]
−
p
r
e
i
c
e
s
[
i
]
,
d
p
[
i
−
1
]
[
1
]
)
;
dp[i][1] = max(dp[i - 1][0] - preices[i], dp[i - 1][1]);
dp[i][1]=max(dp[i−1][0]−preices[i],dp[i−1][1]);
其
中
:
d
p
[
0
]
[
0
]
=
0
,
d
p
[
0
]
[
1
]
=
−
p
r
i
c
e
[
0
]
;
其中:dp[0][0] = 0, dp[0][1] = -price[0];
其中:dp[0][0]=0,dp[0][1]=−price[0];
题解:
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
length = len(prices)
dp = [[0, 0] for i in range(length)]
dp[0][1] = -prices[0]
for i in range(1, length):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee)
dp[i][1] = max(dp[i - 1][0] - prices[i], dp[i - 1][1])
return dp[length - 1][0]