Leetcode_1_Array_123_Best Time to Buy and Sell Stock III

开发出来一个超时版本。从中吸取的教训就是不要轻易使用递归,节约时间成本的意识要加强。

Code:

class Solution(object):
    
    def maxProfit_1(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit_1=0
        min_price=float('inf')
        for i in range(len(prices)):
            min_price=min(min_price,prices[i])
            max_profit_1=max(max_profit_1,prices[i]-min_price)
        return max_profit_1
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        possible_profit=[]
        for i in range(len(prices)-1):
            for j in range(i+1,len(prices)):
                if prices[j]>prices[i]:
                    a=self.maxProfit_1(prices[i:j+1])
                    b=self.maxProfit_1(prices[j+1:])
                    c=sum([a,b])
                    possible_profit.append(c)
        if len(possible_profit)==0:
            return 0
        elif len(possible_profit)==1:
            return possible_profit[0]
        return max(possible_profit)

 

正确版本:

1.作者用到了动态规划(Dynamic Programming,DP)思想,思路异常清晰,就是选用了两个实时变化的量:一个代表当前时刻卖出股票可挣得的最大利润金额;一个代表当前时刻购买股票可挣得的最大利润金额。分别置于两个列表中,再叠加找出最大值即可。

2.另外,为了节约时间成本,作者坚持只用一个for 循环,一个实时变量从蛇头遍历,另一个从蛇尾开始遍历。

Code:

class Solution(object):
    
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        sell,buy,n,minp,maxp=[0],[0],len(prices),prices[0],prices[-1]
        for i in range(1,n):
            minp=min(minp,prices[i])
            maxp=max(maxp,prices[n-1-i])
            sell.append(max(sell[-1],prices[i]-minp))
            buy.append(max(buy[-1],maxp-prices[n-1-i]))
        return max([sell[i]+buy[n-1-i]for i in range(n)])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值