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).

  • 相关阅读:
    第九篇 python基础之函数,递归,内置函数
    第六篇:python基础之文件处理
    第五篇:python基础之字符编码
    第四篇:python基础之条件和循环
    第三篇:python基础之数据类型与变量
    第二篇:python基础之核心风格
    第一篇:初识Python
    作业
    作业3
    作业2
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5388729.html
Copyright © 2011-2022 走看看