买卖股票的最佳时机,求最大收益

in Algorithm with 0 comment

Best Time to Buy and Sell Stock

前提要求

  1. 给出一个每天股票价格的数组,求出最大收益

    Input: [7,1,5,3,6,4]
    Output: 7
    Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
                 Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
    
  2. 不能同时进行交易,必须买完在卖,不能一直卖

解决方案

var maxProfit = function(prices) {
    
    var length = prices.length;
    if (length <= 1) return 0;
    var profit = 0;
    
    for (var i = 1; i < length; i++) {
        // 股价高减去股价低的值大于零
        profit += Math.max(0, prices[i] - prices[i-1])
    }
    
    return profit;
    
};

思路