from typing import Listclass Solution: def maxProfit(self, prices: List[int]) -> int: length = len(prices) if length <= 1:return 0 dp=[ [[0,0,0],[0,0,0] ] for i in range(0,length) ] # 第一天不買入 dp[0][0][0] = 0 # 第一天不買入 dp[0][1][0] = -prices[0] # 第一天不可能有賣出 dp[0][0][2] = float("-inf") dp[0][0][1] = float("-inf") # 第一天一樣不可能即持股,又賣出 dp[0][1][2] = float("-inf") dp[0][1][1] = float("-inf") for index in range(1,length): # 沒有持股和賣出,利潤爲0 dp[index][0][0] = 0 # 持股不賣出,有多是今天持股,有可能昨天已經持股 dp[index][1][0] = max(dp[index - 1][0][0] - prices[index],dp[index - 1][1][0]) # 今天沒有股票且賣出兩次,有多是今天賣出,也有多是昨天就賣出 dp[index][0][2] = max(prices[index] + dp[index - 1][1][1],dp[index - 1][0][2]) # 今天沒有股票且賣出一次,有多是今天賣出,也有多是昨天賣出 dp[index][0][1] = max(prices[index] + dp[index - 1][1][0],dp[index - 1][0][1]) # 今天有股票且賣出一次,有多是今天買入,有多是昨天就買入 dp[index][1][1] = max(dp[index - 1][0][1] - prices[index],dp[index - 1][1][1]) # 今天有股票且賣出兩次,不可能 dp[index][1][2] = float("-inf") print(dp) return max(dp[-1][0][2],dp[-1][0][1],dp[-1][0][0]) # 經過正序和逆序遍歷求出兩個最大利潤,而後相加找出最大的那個。 # 第二個答案不是很懂,不知道怎麼證實其正確性 def maxProfit(self, prices: List[int]) -> int: length = len(prices) if length <= 1:return 0 min_price,max_price = prices[0],prices[-1] profit1,profit2 = [0] * length,[0] * length for index in range(1,length): min_price = min(min_price,prices[index]) profit1[index] = max(profit1[index - 1],prices[index] - min_price) max_price = max(max_price,prices[length - 1 - index]) profit2[length - index - 1] = max(profit2[length - index],max_price - prices[length - index - 1]) profit = profit1[-1] for index in range(length): profit = max(profit1[index] + profit2[index],profit) return profitA = Solution()print(A.maxProfit([3,3,5,0,0,3,1,4]))print(A.maxProfit([1,2,3,4,5]))