Skip to content

Latest commit

 

History

History
16 lines (16 loc) · 613 Bytes

123.md

File metadata and controls

16 lines (16 loc) · 613 Bytes
const maxProfit = function (prices) {
  // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/39611/Is-it-Best-Solution-with-O(n)-O(1).
  let buy0 = Number.MIN_SAFE_INTEGER, buy1 = Number.MIN_SAFE_INTEGER, sell0 = 0, sell1 = 0;
  // const table = []
  for (let i = 0; i < prices.length; i++) {
    buy0 = Math.max(buy0, -prices[i]);
    sell0 = Math.max(sell0, buy0 + prices[i]);
    buy1 = Math.max(buy1, sell0 - prices[i]);
    sell1 = Math.max(sell1, buy1 + prices[i]);
    // table.push([prices[i], buy0, sell0, buy1, sell1]);
  }
  // console.table(table);
  return sell1;
};