Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Feb 27, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接: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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant