chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:121. 买卖股票的最佳时机,暴力法,JavaScript,详细注释

chencl1986 opened this issue · comments

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

解题思路:

  1. 当遇到第i天的价格,只需要考虑它和之后所有价格进行交易产生的利润,并取最大值即可。
  2. 可以使用两层循环,第一层枚举第i天的价格,第二层枚举其之后的价格,并进行计算。
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  let max = 0; // 存储最大利润

  // 第一次遍历,假设已按第i个价格买入了股票
  for (let i = 0; i < prices.length - 1; i++) {
    // 第二次遍历,枚举i之后的所有价格
    for (let j = i + 1; j < prices.length; j++) {
      // 计算当前利润,并与已存储的最大值对比,去较大者
      max = Math.max(prices[j] - prices[i], max);
    }
  }

  return max;
};