题目
题解
labuladong的状态图解
class Solution:
def maxProfit(self, prices: List[int]) -> int:
N = len(prices)
# 定义状态:dp[i][j]表示在第i天持有或卖出时的最大利润,j=1代表持有,j=0代表卖出
dp = [[0 for j in range(2)] for i in range(N)]
for i in range(N):
# badcase
if i - 1 == -1:
dp[i][0] = 0
dp[i][1] = -prices[i]
else:
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
return dp[N-1][0]