123. Best Time to Buy and Sell Stock III

参考了别人的思想,大概是两重动态规划问题,一个值记录前i天profit最大值,另一个值记录i天以后最大值,两者合一即为最大买买次数为2的时候的最大值。代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0 or len(prices) == 1:
            return 0
        pre_profit = [0 for i in range(len(prices))]
        pro_profit = [0 for i in range(len(prices))]
        min_buy = prices[0]
        pre_profit[0] = 0
        for i in range(1, len(prices)):
            min_buy = min(min_buy,prices[i])
            pre_profit[i] = max(pre_profit[i-1], prices[i]- min_buy)
        pro_profit[len(prices)- 1] = 0
        max_sell = prices[-1]
        for j in range(len(prices)-2,-1,-1):
            max_sell = max(max_sell, prices[j])
            pro_profit[j] = max(pro_profit[j+1], max_sell - prices[j])
        profit = 0
        for i in range(len(prices)):
            profit = max(profit, pre_profit[i] + pro_profit[i])
        return profit 

你可能感兴趣的:(123. Best Time to Buy and Sell Stock III)