Я написал функцию для определения максимальной прибыли от ровно k транзакций, транзакция состоит из покупки по низкой цене и продажи по более высокой цене: «вы не можете покупать и продавать в один и тот же день и должны завершить sh одну транзакцию». перед другим, например, заданным [100, 180, 260, 310, 40, 535, 695], 2 должно вернуть 865 Покупать в день: 0 Продавать в день: 3 Покупать в день: 4 Продавать в день: 6, общая покупка = 140, общая продажа = 105, максимальная прибыль = 865 Я написал для этого функцию, но она возвращает пустой массив
function maxProfit(price, k) {
// check for the availability of at least two prices and 1 transaction
if ((k = 0 || price.length < 1)) return 0;
// Initialize the profit;
let profit = [];
//Create count for each cycle of transaction
for (let t = 1; t <= k; t++) {
for (let i = 0; i < price.length; i++) {
// Find the day's Minimal by comparing present element to the next element
if (price[i + 1] <= price[i]) i++;
// When you find the first minimal then Find another day's Maximal
else
for (let j = i + 1; j <= price.length; j++) {
// The day you find a higher price than you bought is the day at which the stock should be sold
if (price[j] > price[i]) {
let curr_profit = price[j] - price[i] + maxProfit(price, t + 1);
// Update the maximum profit so far
profit = Math.max(profit, curr_profit);
}
}
}
}
// Update the profit so far
return profit;
}
//This is returning an empty array and I can't figure out why