I tried to solve it but my solution is wrong with the test number 15
my code
function maxProfitWithKTransactions(pricesArr, k) {
if(pricesArr.length === 0) return 0;
var maxProfit = [];
var buyPrice = 0;
var sellPrice = 0;
var buyPriceIndex = 0;
var changeBuyPrice = true;
for (var i = 0; i < pricesArr.length; i++) {
if (changeBuyPrice){
buyPrice = pricesArr[i];
buyPriceIndex = i;
maxProfit[buyPriceIndex] = 0;
}
sellPrice = pricesArr[i + 1];
if (sellPrice < buyPrice) {
changeBuyPrice = true;
}
else {
var tempProfit = sellPrice - buyPrice;
if (tempProfit > maxProfit[buyPriceIndex]){
maxProfit[buyPriceIndex]= tempProfit;
changeBuyPrice = false;
}else changeBuyPrice = true;
}
}
return maxProfit.sort((a,b) => a<b).slice(0,k).reduce((a,b)=>a+b);
}
THE Problems link https://www.algoexpert.io/questions/Max%20Profit%20With%20K%20Transactions