Leetcode 121 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.

维护存储最小值的变量和最大利润的变量。

*empty list in python evalutes to be false. in Ruby -> true.

class Solution:
    # @param {integer[]} prices
    # @return {integer}
    def maxProfit(self, prices):
        if len(prices)==1 or not prices:
            return 0
        stock, maximun_profit = prices[0], 0
        for i in range(len(prices)):
            if prices[i] < stock:
                stock = prices[i]
            else:
                maximun_profit = max(maximun_profit, prices[i] - stock)
        return maximun_profit

 简化版本

class Solution(object):
    def maxProfit(self, prices):
        if not prices:
            return 0
        profit, mp = 0, prices[0]
        for i in range(len(prices)):
            mp = min(prices[i],mp)
            profit = max(profit,prices[i]-mp)
        return profit
posted @ 2015-07-03 09:06  lilixu  阅读(124)  评论(0编辑  收藏  举报