function f(idx, buy, prices, cap, n) {
if (cap == 0) {
return 0;
}
if (idx == n) {
return 0;
}
let profit = 0;
// You can either buy or not buy
if (buy == 0) {
profit = Math.max(
-prices[idx] + f(idx + 1, 1, prices, cap, n),
f(idx + 1, 0, prices, cap, n)
);
}
// You can either sell or not sell
else {
profit = Math.max(
prices[idx] + f(idx + 1, 0, prices, cap - 1, n),
f(idx + 1, 1, prices, cap, n)
);
}
return profit;
}
function maxtwobuysell(prices, n) {
return f(0, 0, prices, 2, n);
}
const arr = [2, 30, 15, 10, 8, 25, 80];
const size = arr.length;
console.log(maxtwobuysell(arr, size));