zoukankan      html  css  js  c++  java
  • 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.

    这题是一系列最佳买卖股票题目当中的第一题,也是最简单的。看题意可明白,买应在卖之前,利润最大,即在前面找到一个价格的最小值,在后面寻找一个最大值获取最大差价。可以维护一个min_price变量用于保存到第i-1天区间中的价格最低值。维护max_profit用于保存到第i-1天区间中的可能的利润最大值。则当第i天的价格低于min_price时,没有可能在第i天卖出获得最大利润,此时更新min_price,为后续的区间求值做准备。而如果第i 天的价格高于min_price,则在这天卖出获得最大值,max_profit(i)=max(max_profit(i-1),prices(i)-min_prices(i-1))。虽然问题简单其实蕴含着动态规划的思想,而在更新min_price时存在贪心的思路。代码如下:

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            if not prices:
                return 0
            max_profit = 0
            min_price = prices[0]
            length = len(prices)
            for i in xrange(1,length):
                if min_price > prices[i]:
                    min_price = prices[i]
                else:
                    max_profit = max(max_profit,prices[i]-min_price)
            return max_profit

    遍历了一遍数组,时间复杂度O(n),空间复杂度O(1).

  • 相关阅读:
    [杂谈]关于前端如何学习框架的一点牢骚
    【2018】面试复习大纲
    迟来的2017总结
    [转载并收藏]JavaScript 疲劳终极指南:我们行业的真相
    想做好产品,一定要成为自己产品的用户
    2017年个人提升计划
    Chrome新发现
    不要被所在的公司或企业绑架
    半夜不想睡有感
    2016年总结
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5388729.html
Copyright © 2011-2022 走看看