121. 买卖股票的最佳时机:
代码思路
dp[i][0] 表示第i天持有股票所得最多现金
dp[i][1] 表示第i天不持有股票所得最多现金
dp[0][0] = -7
dp[0][1] = 0
当第i天继续持有,一共两种状态:还有就是之前就买入, 第i天才买入
分别是 dp[i][0] : dp[i-1][0] 和 -prices[i]
当第i天不持有,也就是第i天那天卖出,或者是之前就卖出了,分别是dp[i - 1][1]和 prices[i]
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# dp[i][1] = max(dp[i - 1][1], prices[i] + dp[i - 1][0])
dp = [[0 for j in range(2)] for i in range(len(prices))]
dp[0][0] = -prices[0]
dp[0][1] = 0
for i in range(1, len(prices)):
dp[i][0] = max(-prices[i], dp[i-1][0])
dp[i][1] = max(prices[i] + dp[i - 1][0], dp[i - 1][1])
return dp[-1][-1]
122.买卖股票的最佳时机II:
代码思路
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
diff = prices[i] - prices[i-1]
if diff > 0:
profit += diff
return profit