Skip to content

Instantly share code, notes, and snippets.

@ilatif
Created September 19, 2020 21:14
Show Gist options
  • Save ilatif/c291ab3165d6cc33514fde171b234f2b to your computer and use it in GitHub Desktop.
Save ilatif/c291ab3165d6cc33514fde171b234f2b to your computer and use it in GitHub Desktop.
let profit = 0;
let profits = {};
function maxProfitWithKTransactions(prices, k) {
// Write your code here.
profit = 0;
mainProfit = 0;
profits = {};
let max = 0;
for (let i = 0; i < prices.length; i++) {
process(prices, i, max, k, 1);
}
console.log(profits);
if (!Object.keys(profits).length) {
return 0;
} else {
let _profit = profits[k * 2];
if (typeof _profit !== 'undefined') {
profit = _profit;
}
}
return profit;
}
function process(prices, index, max, k, transactions) {
for (let i = index + 1; i < prices.length; i++) {
var temp = 0;
if (prices[i] < prices[index]) {
temp = max;
} else {
temp = max + prices[i] - prices[index];
}
if (temp > profit) {
profit = temp;
}
if (typeof profits[transactions] === "undefined") {
profits[transactions] = 0;
}
if (temp > profits[transactions]) {
profits[transactions] = temp;
}
process(prices, i, temp, k, transactions + 1);
}
}
// Do not edit the line below.
exports.maxProfitWithKTransactions = maxProfitWithKTransactions;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment