【LeetCode with Python】 Best Time to Buy and Sell Stockd

来源:互联网 发布:sql删除数据库字段 编辑:程序博客网 时间:2024/06/16 08:18

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 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: 0In this case, no transaction is done, i.e. max profit = 0.
     题目的意思就是你先买后卖,所以不是简单最大值最小值相差,因为最大值不能在第一位。


class Solution:    # @param prices, a list of integer    # @return an integer    def maxProfit(self, prices):        if None==prices or len(prices)<2:            return 0        min=prices[0]      #  print len(prices)        max_diff=0        for i in range(1,len(prices)):            if prices[i-1]<min:              #因为一定买的比卖的贵                min=prices[i-1]                print min       #     print i       #     print prices[i-1]            cur_diff=prices[i-1]-min                        if cur_diff>max_diff:                max_diff = cur_diff        return max_diffprices=[82,2,44,1,1,3,2,7,4,5,7,6]print Solution().maxProfit(prices)




0 0
原创粉丝点击