1. 程式人生 > >python leetcode Best Time to Buy and Sell Stock

python leetcode Best Time to Buy and Sell Stock

經典的關於陣列的DP題目

121. Best Time to Buy and Sell Stock

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if prices==[]:
            return 0
        res=0
        mymin=prices[0]
        mymax=prices[0]
        for
i in range(1,len(prices)): if prices[i]>mymax: mymax=prices[i] res=max(res,mymax-mymin) if prices[i]<mymin: mymax=prices[i] mymin=prices[i] return res

122. Best Time to Buy and Sell Stock II 在最高價時賣出更新最大最小值

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if prices==[]:
            return 0 
        buy=False
        res=0
        mymax=mymin=prices[0]
        for n in prices:
                if n < mymax:
                    res+=
mymax-mymin mymax=mymin=n elif n < mymin: mymin=mymax=n elif n > mymax: mymax=n res+=mymax-mymin return res

123. Best Time to Buy and Sell Stock III 只能進行最多兩次交易,那麼一次從頭遍歷,一次從尾遍歷

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        #p[i] 0~i 進行一次交易的最大利潤  
        #q[j] j~n  進行一次交易的最大利潤
        ln = len(prices)
        if ln<=1:
            return 0 
        p=[0]*ln
        q=[0]*ln
        minv=prices[0]
        for i in range(1,ln):
            minv=min(minv,prices[i])
            p[i]=max(p[i-1],prices[i]-minv)
        
        maxv=prices[-1]
        for j in range(ln-2,-1,-1):
            maxv=max(prices[j],maxv)
            q[j]=max(q[j+1],maxv-prices[j])
        res=0
        for i in range(ln):
            res=max(p[i]+q[i],res)
        return res

188. Best Time to Buy and Sell Stock IV 難題來了,如何設計DP和動態轉移方程。

class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        n=len(prices)
        res=0
        if n<2: return 0 
        if k>n//2:
            for i in range(n-1):
                if prices[i+1]-prices[i]>0:
                    res+=prices[i+1]-prices[i] 
            return res  
        #買入後 或者 賣出後手裡的錢
        hold=[-2**31]*(k+1)
        sold=[0]*(k+1)
        for price in prices:
            for j in range(1,k+1):
                #要不要持有 只有賣出當前的股票後 才能繼續持有新的股票
                hold[j]=max(hold[j],sold[j-1]-price)
                sold[j]=max(sold[j],hold[j]+price)
                #要不要賣出 
        return sold[k]