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]

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84974787