Original link: leetcode-cn.com/problems/be…

Answer:

For day I, we need to know two states:

  1. from0toiDay, the lowest price of the stock, withcostRepresents, i.ecost = Math.min(cost, prices[i]);
  2. In the firstiThe profit from selling the stock in one dayprofitRepresents, i.eprofit = prices[i] - cost. We can relate it to0toi - 1Days of maximum profit comparison, then traversal when completeprofitThat’s maximum profit, which is zeroprofit = Math.max(prices[i] - cost, profit);
/ * * *@param {number[]} prices
 * @return {number}* /
var maxProfit = function (prices) {
  let cost = prices[0]; // Minimum cost of buying stock from day 1 to day I
  let profit = 0; // Maximum profit from selling stock from day 1 to day I

  // Recurse through prices starting at 1
  for (let i = 1; i < prices.length; i++) {
    // The minimum known price up to I is the smaller of the minimum known price before I and the current price
    cost = Math.min(cost, prices[i]);
    // The maximum profit generated up to I is the greater of the maximum profit generated before I and the maximum profit currently sold
    profit = Math.max(prices[i] - cost, profit);
  }

  // Recursion to the end maximizes profit
  return profit;
};
Copy the code