1. Title Description

Second, train of thought analysis

You can only make two purchases and no more than one transaction on the same day. If a second transaction is made, which must be based on the first one, we can use res[0], RES [1], RES [2],res[3] to represent the first buy, the first sell, the second buy, and the second sell to obtain the following state transition equation:

Res [3]= RES [2] + offer price res[2]= RES [1] – Offer price res[1]= RES [0] + Offer price res[0]= – Offer price

var maxProfit = function (prices) {
  // Note the initial state, the first and third buy, initialize 1 and 3 to -infinity;
  const res =[-Infinity.0, -Infinity.0]
  for (let i = 0; i < prices.length; ++i) {
    res[3] = Math.max(res[3], res[2] + prices[i]);
    res[2] = Math.max(res[2], res[1] - prices[i]);
    res[1] = Math.max(res[1], res[0] + prices[i]);
    res[0] = Math.max(res[0], -prices[i]);
  }

  return Math.max(res[1], res[3]);
};
Copy the code

Reference: zhuanlan.zhihu.com/p/76039990

Third, summary

The hard part is to understand the idea and sort out the state transition equation.