[LeetCode] 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.

 

Invariant 在于,如果第i 天和第j 天分别是最高收益的买入点和卖出点,那么prices[i] 必然是[0, j] 区间内价格的最低点。

只用遍历一次,用当前找到的最低价格来计算收益,并更新收益最大值,同时更新价格最低点。遍历完成之后即得结果。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var n = 0;
    var lowest = prices[0];
    prices.forEach(function(p) {
        n = Math.max(n, p - lowest);
        lowest = Math.min(lowest, p);
    });
    return n;
};

 

posted @ 2016-04-19 12:17  Agentgamer  阅读(105)  评论(0编辑  收藏  举报