T121 买卖股票的最佳时机

桌桌 2022-8-12 221 8/12

题目描述如下:

T121 买卖股票的最佳时机

解题思路:

这部遍历看看?(明知应该会超时)

代码如下:

class Solution:
   def maxProfit(self, prices: List[int]) -> int:
       length = len(prices)
       maxXmin = 0
       for i in range(length-1):
           for j in range(i+1, length):
               if prices[j]-prices[i] > maxXmin:
                   maxXmin = prices[j]-prices[i]
       return maxXmin

结果如下:

T121 买卖股票的最佳时机

果然超时了,那么想想哪里耗时多了呢?好像每次的操作都是没有多余无用的操作,都是检查一个可能的解

那么肯定哪里可以进行优化

一看测试用例,已经到198/211了,其实也就是最后几个用例

看了下超时的用例,是对于有序列的数据,那么我们可以对这样的有顺序输入进行算法上的优化:

考虑了一下可以使用单调栈的数据结构

代码如下:

class Solution:
   def maxProfit(self, prices: List[int]) -> int:
       mystack = [-1]
       length = len(prices)
       maxXmin = 0
       i = 0
       while i < length or mystack != [-1]:
​
           if i < length and prices[i] > mystack[-1]:
               mystack.append(prices[i])
               i += 1
           elif i < length and prices[i] == mystack[-1]:
               i += 1
               continue
           else:
               topNum = mystack.pop()
               if mystack == [-1]:
                   continue
               elif maxXmin < topNum - mystack[1]:
                   maxXmin = topNum - mystack[1]
​
       return maxXmin

结果如下:

T121 买卖股票的最佳时机

- THE END -

桌桌

8月16日01:08

最后修改:2022年8月16日
0

非特殊说明,本博所有文章均为博主原创。

共有 7 条评论

  1. freespin

    When some one searches for his required thing, thus he/she wants to be available that in detail, therefore that thing is maintained over here. Domenic Hojczyk

  2. Loveme

    Wonderful post! We will be linking to this great article on our site. Keep up the good writing. Rex Sitsler

  3. Anna94 wants to trade nude pics with you

    Great message for all the people. And also very interesting facts about the plastic surgery. Grover Ballog

  4. russian bet

    Hi, I would like to subscribe for this blog to get most recent updates, thus where can i do it please help. Garrett Schlottman

  5. russian bet

    Way cool! Some extremely valid points! I appreciate you writing this write-up and the rest of the website is also very good. Jon Sarcinella

  6. freespin

    Asking questions are truly nice thing if you are not understanding anything completely, but this article offers good understanding yet. Jack Louwagie

  7. bahis oyna

    Im thankful for the blog post. Really thank you! Really Great. Richard Grodi