zoukankan      html  css  js  c++  java
  • 121. 买卖股票的最佳时机

     

     思路:

    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]))
    
    
    
     
  • 相关阅读:
    02-zabbix安装部署
    01-zabbix服务说明
    00-ContOS 7.5编译安装MySQL-5.7.30
    bitset习题
    数颜色[分块]
    旋转子段 (思维stl)
    双栈排序(洛谷P1155)二分图的判定+思维贪心
    常见的系统获取唯一码方式
    SHELL-数组
    Prometheus-alertmanager组件使用
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12723174.html
Copyright © 2011-2022 走看看