1. 程式人生 > >【python/Hard/leetcode/123】Best Time to Buy and Sell Stock III

【python/Hard/leetcode/123】Best Time to Buy and Sell Stock III

題目

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

基本思路

開闢兩個陣列p1和p2

p1[i]表示在price[i]之前進行一次交易所獲得的最大利潤,
p2[i]表示在price[i]之後進行一次交易所獲得的最大利潤。

則p1[i]+p2[i]的最大值就是所要求的最大值,

實現程式碼

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
n = len(prices) if n <= 1: return 0 p1,p2 = [0] * n,[0] * n minV = prices[0] for i in range(1,n): minV = min(minV,prices[i]) p1[i] = max(p1[i-1],prices[i]-minV) maxV = prices[-1] for
i in range(n-2,-1,-1): maxV = max(maxV,prices[i]) p2[i] = max(p2[i+1],maxV-prices[i]) res = 0 for i in range(n): res = max(res,p1[i]+p2[i]) return res