Моя функция найти максимальную прибыль с k транзакциями возвращает пустой массив - PullRequest
0 голосов
/ 03 февраля 2020

Я написал функцию для определения максимальной прибыли от ровно 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

Ответы [ 2 ]

0 голосов
/ 03 февраля 2020

Попробуйте:

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 =0;

   //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++
            else
                // When you find the first minimal then Find another day's Maximal
                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);   
                    } 
                }

        }

   }
    let profitArr = [profit];
       // Update the profit so far
       return profitArr
   }

Это просто сохранение значения прибыли в виде массива, потому что вы никогда не выполняли никаких действий с массивом

0 голосов
/ 03 февраля 2020

В строке 2 (оператор If) вместо оператора равенства вы использовали оператор присваивания.

При k = 0 выполнение никогда не попадет в for для l oop " для (пусть t = 1; t <= k; t ++)</strong>"

 if ((k = 0 || price.length < 1)) return 0; // old
 if ((k == 0 || price.length < 1)) return 0; // new

Кроме того, для лучшей оптимизации лучше удалить хвостовую рекурсию.

let curr_profit = price[j] - price[i] + maxProfit(price, t + 1);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...