Skip to content

买卖股票的最佳时机

LeetCode-122

js
// 时间复杂度:O(n),其中 n 为数组长度,只需要遍历一次即可
// 空间复杂度:O(1),只需要常数的空间存放若干变量
var maxProfit = function (prices) {
  let maxProfit = 0
  for (let i = 1; i < prices.length; i++) {
    // 只需要判断前一天跟当天的价格做对比
    if (prices[i] > prices[i - 1]) {
      // 若当天的价格比前一天的高,则前一天买入并在当天卖出,获得收益
      maxProfit += (prices[i] - prices[i - 1])
    }
  }
  return maxProfit
}