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.

# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
    return 0 if prices.empty? || prices.length == 1
    l, m = prices[0], 0
    prices.each do |x|
        if x < l
            l = x
        else
            m = x - l > m ? x-l : m
        end
    end
    m
end


你可能感兴趣的:(LeetCode)