Created
September 19, 2020 21:14
-
-
Save ilatif/c291ab3165d6cc33514fde171b234f2b to your computer and use it in GitHub Desktop.
AlgoExpert Max Profit with k Transactions - https://www.algoexpert.io/questions/Max%20Profit%20With%20K%20Transactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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