Skip to content

LeetCode题解:121. 买卖股票的最佳时机,JavaScript,动态规划,详细注释 #303

@chencl1986

Description

@chencl1986

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

解题思路:

对于第i天,我们需要知道两种状态:

  1. 0i天,股票最低价格,用cost表示,即为cost = Math.min(cost, prices[i]);
  2. 在第i天卖出股票能获得的利润,用profit表示,即为profit = prices[i] - cost。我们可以将其与0i - 1天的最大利润对比,那么遍历完成时profit就是最大利润,即为profit = Math.max(prices[i] - cost, profit);
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  let cost = prices[0]; // 从第一天到第i天买入股票的最小花费
  let profit = 0; // 从第一天到第i天卖出股票的最大利润

  // 从1开始遍历prices进行递推
  for (let i = 1; i < prices.length; i++) {
    // 到i为止已知的最小价格,是i之前已知的最小价格,与当前价格之间的较小者
    cost = Math.min(cost, prices[i]);
    // 到i为止产生的最大利润,是i之前产生的最大利润,与当前卖出的最大利润中的较大者
    profit = Math.max(prices[i] - cost, profit);
  }

  // 递推到最后就得到了最大利润
  return profit;
};

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