121 Best Time to Buy and Sell Stock

数组中的元素代表当天的股票价格,一次买卖,设计算法找到买入卖出的最大利润。

  • 时间复杂度O(n),空间复杂度O(1)

动态规划求解

  • Runtime: 80 ms, faster than 74.53%
  • Memory Usage: 37.6 MB, less than 27.40%
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var min = prices[0]
    var max = 0
    for(var i = 1; i < prices.length; i++){
        max = Math.max(max, prices[i] - min)
        min = Math.min(min, prices[i])
    }
    return max
};
  • Runtime: 72 ms, faster than 94.04%
  • Memory Usage: 37.4 MB, less than 57.91%
var maxProfit = function(prices) {
    let len = prices.length
    let diff = 0
    let min = prices[0]
    for (let i = 1; i < len; i++) {    
        let temp = prices[i] - min
        if(temp > diff) diff = temp
        if(prices[i] < min) min = prices[i]
    }
    return diff
};

你可能感兴趣的:(121 Best Time to Buy and Sell Stock)