码迷,mamicode.com
首页 > 其他好文 > 详细

121. 买卖股票的最佳时机

时间:2020-04-17 23:54:09      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:pre   false   ted   print   div   tin   sof   mic   http   

技术图片

 

 技术图片

 

 思路:

1、将prices升序排列;
2、用price遍历排序后的prices,取price在原list中的下标i;
3、在原list中截取下标i之后的元素,取其中最大值max(temp[i:]);
4、计算当前利润:max(temp[i:]) - price,存入ans[]中;
5、返回ans中的最大值。
 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         # 存放利润,返回其中最大值
 8         ans = []
 9         # 用temp暂存原list
10         temp = prices
11         # 升序排列
12         prices = sorted(prices, reverse=False)
13         # 没有交易完成,利润为0
14         if prices[::-1] == temp:
15             return 0
16         # 遍历升序排列的prices
17         for price in prices:
18             # 取当前price在原list中的下标
19             i = temp.index(price)
20             # 如果最低价是原list的最后一个元素,跳过
21             if i == len(temp) - 1:
22                 continue
23             # 取i往后的最大价格与当前价格作差,即利润,存入ans中
24             ans.append(max(temp[i:]) - price)
25         return max(ans)
26 
27 
28 if __name__ == __main__:
29     solution = Solution()
30     print(solution.maxProfit([7, 1, 5, 3, 6, 4]))

 

 

121. 买卖股票的最佳时机

标签:pre   false   ted   print   div   tin   sof   mic   http   

原文地址:https://www.cnblogs.com/panweiwei/p/12723174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!