首页 > 其他 > 详细

[LeetCode] Best Time to Buy and Sell Stock

时间:2016-04-19 13:59:13      阅读:145      评论:0      收藏:0      [点我收藏+]

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;
};

 

[LeetCode] Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/agentgamer/p/5407680.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!