zoukankan      html  css  js  c++  java
  • 121. Best Time to Buy and Sell Stock(股票最大收益)

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Example 1:

    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    
    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
    

    Example 2:

    Input: [7, 6, 4, 3, 1]
    Output: 0
    
    In this case, no transaction is done, i.e. max profit = 0.
    

     暴力超时:

     1 class Solution:
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         n = len(prices)
     8         if n==0:
     9             return 0
    10         max_diff = 0
    11         for i in range(n):
    12             for j in range(i,n):
    13                 diff = prices[j]-prices[i]
    14                 if diff>max_diff:
    15                     max_diff = diff
    16                     
    17         return max_diff
    18 
    19         

    只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o….i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

    class Solution:
        def maxProfit(self, a):
            """
            :type prices: List[int]
            :rtype: int
            """
            n = len(a)
            if n==0:
                return 0
            mins = a[0]
            max_diff = 0
            for i in range(1,n):
                #买入价也可以看成是卖出价
                
                #找到到截止到第i天的最低买入价
                if(a[i]<mins):
                    mins = a[i]
                # 更新最大收益
                elif max_diff < a[i] - mins:
                    max_diff = a[i] - mins
            return max_diff
    
            
  • 相关阅读:
    LNMP状态管理命令
    Gogs基本使用介绍
    初探Asp.net请求机制原理 1
    关于css定位
    JS不同浏览器图片载入处理
    js之队列01
    javascript 快速排序
    JavaScript prototype背后的工作原理
    关于javascrpt if快速判断说明
    js动态加载图片核心代码
  • 原文地址:https://www.cnblogs.com/zle1992/p/8743577.html
Copyright © 2011-2022 走看看