https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/comments/
dp1[i] = max(dp[i-1], prices[i] - minval) 从前往后遍历,表示第1天到第i天之间的最大利润(通过是否在第i天卖出确认);
dp2[i] = max(dp[i+1], maxval - prices[i]) 从后往前遍历,表示第i天到最后一天之间的最大利润(通过是否在第i天买进确认);
res = max(dp1 + dp2),因为(dp1 + dp2)[i] 正好表示从第1天到最后一天经过两次交易的最大利润,我们的目标是找到令总利润最大的i。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n < 2:
return 0
dp1 = [0 for _ in range(n)]
dp2 = [0 for _ in range(n)]
minval, maxval = prices[0], prices[n-1]
#前向
for i in range(1, n):
dp1[i] = max(dp1[i-1], prices[i] - minval)
minval = min(minval, prices[i])
#后向
for i in range(n-2, -1, -1):
dp2[i] = max(dp2[i+1], maxval - prices[i])
maxval = max(maxval, prices[i])
#合并
dp = [dp1[i] + dp2[i] for i in range(n)]
return max(dp)