怎么定义dp数组大有门道。
121. 买卖股票的最佳时机
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 需要二维数组来记录
# [0]持有股票和[1]不持有股票
if len(prices) == 0:
return 0
dp = [[0,0] for _ in range(len(prices))]
dp[0][0] = -prices[0]
for i in range(1, len(prices)):
dp[i][0] = max(dp[i-1][0], -prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i])
return dp[-1][1]
122.买卖股票的最佳时机II
leetcode 122.买卖股票的最佳时机II
代码随想录
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 需要二维数组来记录
# [0]持有股票和[1]不持有股票
if len(prices) == 0:
return 0
dp = [[0,0] for _ in range(len(prices))]
dp[0][0] = -prices[0]
for i in range(1, len(prices)):
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[-1][1]
123.买卖股票的最佳时机III
leetcode 123.买卖股票的最佳时机III
代码随想录
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 需要二维数组来记录
# 0不操作、1第一次持有股票、2第一次不持有股票 3 第二次持有股票 4第二次不持有股票
if len(prices) == 0:
return 0
dp = [[0,0,0,0,0] for _ in range(len(prices))]
dp[0][1] = -prices[0]
dp[0][3] = -prices[0]
for i in range(1, len(prices)):
dp[i][0] = dp[i-1][0]
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
dp[i][2] = max(dp[i-1][2], dp[i-1][1] + prices[i])
dp[i][3] = max(dp[i-1][3], dp[i-1][2] - prices[i])
dp[i][4] = max(dp[i-1][4], dp[i-1][3] + prices[i])
return dp[-1][-1]