【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])

原文地址:https://www.cnblogs.com/kwangeline/p/5953502.html