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
  • 相关阅读:
    《Android 4游戏高级编程(第2版)》书评
    push研究——Apache Mina探索初步
    Android UI开发第二十三篇——分享书架UI实现
    cookie学习总结
    Web.xml配置详解
    Java序列化的机制和原理
    Java高级技术(汇总中...)
    [Java]HashMap的两种排序方式
    jdk与jre的区别
    DM,NLP常用算法汇总
  • 原文地址:https://www.cnblogs.com/yawenw/p/12261726.html
Copyright © 2011-2022 走看看