Leecode 122.买卖股票的最佳时机

题目

在这里插入图片描述

题解

一次遍历
首先需要考虑prices为空列表,则返回0
基本思路:从前向后遍历列表,首先min_price=prices[0],当列表出现更低价格时候替换min_price,最大利润max_profit初始值为0,之后取值为max(max_profit,当前价格-之前最低价格)。最后返回max_profit

class Solution(object):    
def maxProfit(self, prices):        
"""        
:type prices: List[int]        
:rtype: int        
"""     
   if prices==[]:         
      return 0        
   min_price=prices[0]
   max_prifit=0
   #遍历列表        
   for i in prices:            
       if min_price>i:
       #替换最低价格               
           min_price=i         
       else:            
           max_prifit=max(max_prifit,i-min_price)        
   return max_prifit        

在这里插入图片描述

发布了47 篇原创文章 · 获赞 5 · 访问量 1896

猜你喜欢

转载自blog.csdn.net/Pang_ling/article/details/104604864