Question: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
Question Name: Best Time to Buy and Sell Stock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | lass Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): # Not enough time to earn profit if len(prices) < 2: return 0 # The maximum price from here to the end maxFromHere = prices[-1] # The maximum profit, we could earn. # Could initialize it with any valid profit. maxProfit = prices[1] - prices[0] for index in xrange(len(prices)-2, -1, -1): price = prices[index] # The maximum profit, if we buy it here. profit = maxFromHere - price maxProfit = max(maxProfit, profit) maxFromHere = max(maxFromHere, price) # If maxProfit is negative, we would not take # any transaction. # # If we initialize the maxProfit with 0, this # step is not necessary. maxProfit = max(0, maxProfit) return maxProfit |