var maxProfit = (prices) => {
let [ sold, held, reset ] = [ (-Infinity), (-Infinity), 0 ];
[ sold, reset ] = search(prices, sold, held, reset);
return Math.max(sold, reset);
}
var search = (prices, sold, held, reset) => {
for (const price of prices) {
const preSold = sold;
sold = (held + price);
held = Math.max(held, (reset - price));
reset = Math.max(reset, preSold);
}
return [ sold, reset ];
}
var maxProfit = (prices) => {
const tabu = initTabu(prices);
search(prices, tabu);
return tabu[0];
}
var initTabu = (prices) => new Array(prices.length + 2).fill(0);
var search = (prices, tabu) => {
for (let i = (prices.length - 1); (0 <= i); i--) {
const prev = buyAndSell(prices, i, tabu);
const next = tabu[i + 1];
tabu[i] = Math.max(prev, next);
}
}
const buyAndSell = (prices, i, tabu, max = 0) => {
for (let sell = (i + 1); (sell < prices.length); sell++) {
const profit = ((prices[sell] - prices[i]) + tabu[(sell + 2)]);
max = Math.max(max, profit);
}
return max;
}