zoukankan      html  css  js  c++  java
  • 【leetcode❤python】121. Best Time to Buy and Sell Stock

    #-*- coding: UTF-8 -*-
    #Method1 :超时
    #class Solution(object):
    #    def maxProfit(self, prices):
    #      
    #        maxprofit=0
    #        for i in xrange(1,len(prices)):
    #            tmprofit=prices[i]-min(prices[0:i])
    #            maxprofit=tmprofit if tmprofit>maxprofit else maxprofit
    #        return maxprofit
    #    
    #sol=Solution()
    #print sol.maxProfit([7, 6, 4, 3, 1])
    #:Method2:动态规划
    ###遍历数组时记录当前价格以前的最小价格curMin,记录昨天能够获得的最大利润maxProfit
    ###对于今天,为了能获得此刻的最大利润,显然只能卖,或者不做任何操作
    ###如果不做任何操作,显然还是昨天maxProfit
    ###如果卖掉今天天的股票,显然prices[i]-curMin
    class Solution(object):
        def maxProfit(self,prices):                                                       
            curMin=prices[0]
            maxProfit=0
            for i in xrange(1,len(prices)):
                maxProfit=max(maxProfit,prices[i]-curMin)
                curMin=min(prices[i],curMin)
            return maxProfit

    sol=Solution()
    print sol.maxProfit([7, 1, 5, 3, 6, 4])

  • 相关阅读:
    如果int x=20, y=5,则语句System.out.println(x+y +""+(x+y)+y); 的输出结果是()
    子父类存在同名成员时super的使用条件
    7mysql高级查询
    1udp编程
    6mysql外键
    4mysql数据表增删改查
    5mysql数据类型
    3mysql数据库操作
    2mysql基本使用
    1mysql安装
  • 原文地址:https://www.cnblogs.com/kwangeline/p/5953502.html
Copyright © 2011-2022 走看看