zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Note that you cannot sell a stock before you buy one.

    Example 1:

    Input: [7,1,5,3,6,4]
    Output: 5
    Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
    Explanation: In this case, no transaction is done, i.e. max profit = 0.

    思路

      在看到这道题的时候,我最先想到的就是使用暴力破解法进行解决,就是对每一天的股票计算出他可以获得的利润,然后取其中最大的值。就可以得到结果。时间复杂度为O(n2),空间复杂度为O(1)。但是这种办法当面对数据非常的多时,会出现超时的情况。因此根据这个情况我改变想法,因为整个过程只能交易一次,所以我们可以从头开始遍历,用min_price记录最低的股票价格,用max_profit获得的最高的利润。从头开始遍历。直到尾部。这种解法的时间复杂度为O(n)。空间复杂度为O(1)。

    解决代码

      第一种思路
     1 class Solution(object):
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         if not prices:
     8             return 0
     9         max_profit = 0        # 最大的利润
    10         for  i in range(len(prices)):        # 从第一个开始遍历
    11             for j in range(i+1, len(prices)):     # 从下一个开始遍历
    12                 if max_profit < (prices[j]-prices[i]):  
    13                     max_profit = prices[j]-prices[i]
    14         return max_profit
      第二种解法
     1 class Solution(object):
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         if not prices:
     8             return 0
     9         min_price, max_profit = float("inf"), 0   # 使用min_price记录最低的股票价格,max_profit记录最高的利润
    10         for i in range(len(prices)):        # 从头开始遍历
    11             if prices[i] < min_price:         # 如果当前股票价格比最低的股票价格还要低,改变最低股票价格值。
    12                 min_price =  prices[i]
    13             elif prices[i] - min_price > max_profit:     # 否则进行判断,当前的利润是否大于得到的最大利润。
    14                 max_profit = prices[i] - min_price
    15         return max_profit
  • 相关阅读:
    《闯关东》群英传
    这老太太
    URL重写与伪静态
    创建索引视图时提示架构绑定无效,名称必须由两部分构成
    马色见
    食神智多星
    Beautiful Code and Beautiful Software
    /wp64 Compiler Option
    C++的x64移植
    Managing the State Data of MFC Modules
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10901912.html
Copyright © 2011-2022 走看看