zoukankan      html  css  js  c++  java
  • leetcode121 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.
    """
    class Solution1(object):
        def maxProfit(self, prices):
            if prices == None or len(prices) < 1:  #先对边界判断,提升代码质量
                return 0
            n = len(prices)
            max_profit = 0
            for i in range(n):
                for j in range(i+1, n):
                    if (prices[j] - prices[i]) > max_profit:
                        max_profit = prices[j] - prices[i]
            return max_profit
    
    """
    这是dp题,此暴力方法超时。
    [10000,9999,9998,9997,9996,...,1]用例超时
    """
    
    """
    解法二:维护两个指标:buy和sell
    去min(buy), max(sell)
    花最少的本钱,获得最多的利润
    进行一次遍历
    """
    class Solution2(object):
        def maxProfit(self, prices):
            if prices == None or len(prices) < 1: #边界条件
                return 0
            buy = prices[0]    #买的初始化为第一个价格
            sell = 0           #利润初始化为0
            for i in range(1, len(prices)):  #从第二个价格开始向后遍历
                buy = min(buy, prices[i])    #找最小的进价
                sell = max(sell, prices[i] - buy)  #更新可以获得的最大利润
            return sell
  • 相关阅读:
    BitmapFactory.decodeStream(inputStream)返回null的解决方法
    android studio 自用快捷键方案
    jquery源码学习(四)—— jquery.extend()
    css3动画性能优化
    组件化开发之vue
    调用本地摄像头并通过canvas拍照
    傳説中的 jsonp
    jsonp的原理
    正确而又严谨得ajax原生创建方式
    让浏览器阻塞10秒钟的方法
  • 原文地址:https://www.cnblogs.com/yawenw/p/12261726.html
Copyright © 2011-2022 走看看