Best Time to Buy and Sell Stock

Posted 唐僧洗发爱飘柔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

    这道题为简单题

  题目:

    

 

  思路:

    这道题我做得有点久了,今天才看见没有写进来,这个挺简单的,min保存最小值,cha最大差值,遍历列表,如果该元素大于min,就cha就等于cha和i-min之间的最大值,如果该元素小于min,那么min就等于i,最后返回cha

  代码:

  

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if len(prices) == 0 or len(prices) == 1:
 8             return 0
 9         min = prices[0]
10         cha = 0
11         for i in prices:
12             if i > min:
13                 cha = max(cha, i - min)
14             if i <= min:
15                 min = i
16         return cha

 

以上是关于Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

最强解析面试题:best-time-to-buy-and-sell-stock

最强解析面试题:best-time-to-buy-and-sell-stock

121. Best Time to Buy and Sell Stock

122. Best Time to Buy and Sell Stock II

123. Best Time to Buy and Sell Stock III***

LeetCode 121. Best Time to Buy and Sell Stock