算法專題訓練(1)股票問題

class Solution(object):
    def maxProfit(self, prices):
        if prices == []: return 0
        minNum,ret = prices[0],0
        for p in prices:
            minNum = min(minNum,p)
            ret = max(ret,p-minNum)
        return ret
  • 122. Best Time to Buy and Sell Stock II:股票多次買入賣出
    思路:判斷第i天和第i-1天的價格差diff,把diff>0部分求和即可
    計算相鄰股票價格的差值,計算差值大於0的元素的和,即爲最大利潤
class Solution(object):
    def maxProfit(self, prices):
        if prices == []: return 0
        ans = 0
        for i in range(1,len(prices)):
            diff = prices[i]-prices[i-1]
            if diff>0:  ans+=diff
        return ans

sell維護買入賣出價格(t[0],t[1]),其中t[1]爲0表示未賣出
如果棧頂未賣出,且price<=buy 替換買入
如果price大於max(賣出價格,買入價格+費用)替換賣出
price作爲買入價格入棧
當棧元素>1,並且合併棧頂的兩組交易可以獲得更大收益時,對棧頂的兩個交易進行合併
a2-a1-fee+b2-b1-fee< b2-a1-fee –> a2
class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        sell = [[50000,0]]
        for price in prices:
            # 如果棧頂未賣出,且price<=buy 替換買入
            if sell[-1][1]==0 and price<sell[-1][0]:
                sell[-1][0] = price
            # 如果price大於max(賣出價格,買入價格+費用)替換賣出
            elif price>=max(sell[-1][0]+fee,sell[-1][1]):
                sell[-1][1] = price
            # price作爲買入價格入棧
            elif sell[-1][1]:
                sell.append([price,0])
            # a2-a1-fee+b2-b1-fee<b2-a1-fee --> a2<b1+fee
            while(len(sell)>1 and sell[-2][1]<sell[-1][0]+fee):
                sell[-1][1] = max(sell.pop()[1],sell[-1][1])
        return sum(t[1]-t[0]-fee for t in sell if t[1]-t[0]>fee)

思路還是偏複雜了。。在kdd的指點,記兩個狀態,買p1和賣p2

p1 = max(p1,p2-price)
p2 = max(p2,p1+price-fee)

class Solution(object):
    def maxProfit(self, prices, fee):
        """
        :type prices: List[int]
        :type fee: int
        :rtype: int
        """
        size = len(prices)
        if size<=1: return 0
        p1,p2 = -prices[0],0
        for i in range(1,size):
            p1 = max(p1,p2-prices[i])
            p2 = max(p2,p1+prices[i]-fee)
        return p2

buy[i]表示時間爲i前操作爲買入的最大收益
sell[i]表示時間爲i前操作爲賣出的最大收益
rest[i]表示時間爲i前操作爲冷凍器的最大收益

buy[i] = max(buy[i-1],rest[i-1]-price) 前一天購買或者前一天冷凍當天購買
sell[i] = max(sell[i-1],buy[i-1]+price) 前一天賣出或者前一天購買當前賣出
rest[i] = max(rest[i-1],buy[i-1],sell[i-1])
buy[i]<=rest[i] 又有 rest[i] = sell[i-1] (因爲rest是在sell操作之後纔有的東西)
所以變成
buy[i] = max(buy[i-1],sell[i-2]-price)
sell[i] = max(sell[i-1],buy[i-1]+price)

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)<2:
            return 0
        sell, buy, prev_sell, prev_buy = 0, -prices[0], 0, 0
        for price in prices:
            prev_buy = buy
            buy = max(prev_sell - price, prev_buy)
            prev_sell = sell
            sell = max(prev_buy + price, prev_sell)
        return sell

計算相鄰股票價格的差值
遍歷i
prev[i]表示從左到右第i位的最大利潤
post[i]表示從右到左第i位的最大利潤
ans=max(ans,prev[i]+post[i])
class Solution(object):
    def maxProfit(self,prices):
        if prices == []: return 0
        size = len(prices)
        MIN,MAX = prices[0],prices[size-1]
        prev,post = [0],[0]
        for i in range(1,size):
            x = prices[i]
            y = prices[size-1-i]
            MAX,MIN = max(MAX,y),min(MIN,x)
            prev.append(max(prev[-1],x-MIN))
            post.append(max(post[-1],MAX-y))
        post.reverse()
        ret = 0
        for i in range(size):
            ret = max(ret,prev[i]+post[i])
        return ret

global G[i][j] 到第i天至多進行j次交易的最優利潤
local G[i][j] 到第i天至多進行j次交易的最優利潤,且在第i天賣出
L[i][j] = max(G[i-1][j-1],G[i-1][j-1]+diff,L[i-1][j]+diff)
說明:
G[i-1][j-1]爲第i-1天進行j-1次交易的最優利潤,在第i天沒有買入賣出行爲
G[i-1][j-1]+diff爲第i-1天進行j-1次交易,然後第i-1天買入,第i天賣出
L[i-1][j]+diff 爲第i-1天進行第j次交易,改爲第i天進行第j次交易
G[i][j] = max(G[i-1][j],L[i][j])
class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        if prices == [] or k ==0 : return 0
        size = len(prices)
        if k>(size/2): return self.maxProfit1(prices)
        L = [[0 for i in range(k+1)] for p in prices]
        G = [[0 for i in range(k+1)] for p in prices]
        for j in range(1,k+1):
            for i in range(1,len(prices)):
                diff = prices[i]-prices[i-1]
                L[i][j] = max(G[i-1][j-1],G[i-1][j-1]+diff,L[i-1][j]+diff)
                G[i][j] = max(G[i-1][j],L[i][j])
        return G[len(prices)-1][k]

    def maxProfit1(self, prices):
        if prices == []: return 0
        ans = 0
        for i in range(1,len(prices)):
            diff = prices[i]-prices[i-1]
            if diff>0:  ans+=diff
        return ans
發佈了196 篇原創文章 · 獲贊 73 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章