【PYTHON-leetcode】121.买卖股票的最佳时机(分治法、动态规划求解)

121.买卖股票的最佳时机

  • 分治法
'''
分治法:
    一分为2,最大收益要么在前一半要么在后一半
    要么跨中心:跨中心采用贪心策略:取前一半最小和后一半最大
迭代结束条件/边界条件:
 1.空集或只有1个元素
 2.2个元素
 由于分治法需要重复求解边界条件,故此处使用动态规划更为适合
'''
    	n=len(prices)
        if n<=1:
            return 0
        if n==2:
            profit=prices[1]-prices[0]
            if profit>0:
                return profit
            else:
                return 0
        mid=n//2
        maxprofit_l=self.maxProfit(prices[0:mid])
        maxprofit_r=self.maxProfit(prices[mid:n])
        #跨中心的例子:
        max_in=min(prices[0:mid])
        max_out=max(prices[mid:n])
        maxprofit_c=max_out-max_in
        return max(maxprofit_c,maxprofit_l,maxprofit_r)
  • 动态规划——时间O(n),空间O(n)——》空间可化简为O(1)
'''
设dp[i]是到第i天的最大收益
默认dp[0]=0
dp[i]=max(dp[i-1],prices[i]-min(prices[0:i-1]))
要求记录minprice
边界条件:
1.序列为空或仅有一个元素
'''
class Solution:
    def maxProfit(self, prices: list) -> int:
        n=len(prices)
        if n<=1 or prices==sorted(prices,reverse=True):
            return 0
        mp=[0]
        #mp=0
        minprice=prices[0] #到第i天的最小价格
        for i in range(1,n):
            mp.append(max(mp[i-1],prices[i]-minprice))
            #if mp<prices[i]-minprice:
            #	mp=prices[i]-minprice          	
            if minprice>prices[i]:
                minprice=prices[i]
        return max(mp)
f=Solution()
l=[7,1,5,3,6,4]
f.maxProfit(l)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章