解题思路:动态规划,dp[i]表示第i天卖出可以获得的最大利润,买入是包括i以及i前面的任意一天,最大利润就是dp[i]中的最大值,状态转移方程为
d
p
[
i
]
=
{
0
d
p
[
i
−
1
]
+
p
r
i
c
e
s
[
i
]
−
p
r
i
c
e
s
[
i
−
1
]
<
0
d
p
[
i
−
1
]
+
p
r
i
c
e
s
[
i
]
−
p
r
i
c
e
s
[
i
−
1
]
o
t
h
e
r
s
dp[i]=\left\{\begin{array}{lr} 0\quad dp[i-1]+prices[i]-prices[i-1] <0\\ dp[i-1]+prices[i]-prices[i-1] \quad others \end{array}\right.
dp[i]={0dp[i−1]+prices[i]−prices[i−1]<0dp[i−1]+prices[i]−prices[i−1]others
如果第i天和第i-1天的利润差加上第i-1天最大利润比零还小,那dp[i]=0,意味着当天买入当天卖出,否则就从前一天可以得到最大利润的方案中多持有一天,到第i天卖出,可以实现第i天卖出利润最大化,代码如下:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
size = len(prices)
if size <= 1:
return 0
dp = [0] * size
for i in range(1, size):
if dp[i-1] + prices[i] - prices[i-1] < 0:
dp[i] = 0
else:
dp[i] = dp[i-1] + prices[i] - prices[i-1]
return max(dp)