码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Best Time to Buy and Sell Stock

时间:2016-04-19 14:00:20      阅读:133      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!