Skip to content

LeetCode 题解:122. 买卖股票的最佳时机 II,JavaScript,一遍循环,详细注释 #104

@chencl1986

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

解题思路:

  1. 我们已经知道了所有时刻的股票价格。
  2. 只需判断如果明天的价格比今天高,则表示需要交易。即今天买入,明天卖出。
  3. 遍历数组,如果n+1天的价格大于第n天,利润就加上两者价格差。
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  let result = 0;

  for (let index = 0; index < prices.length - 1; index++) {
    // 计算当前价格与下一天价格的差值
    const dif = prices[index + 1] - prices[index];
    // 如果下一天的股票价格更高,则表示需要进行交易
    if (dif > 0) {
      // 保存赚取的差价
      result += dif;
    }
  }

  return result;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions