我的函数用k次交易找到最大利润返回一个空数组

问题描述 投票:-1回答:1

我编写了一个函数,可以从恰好k笔交易中找到最大利润,这笔交易包括以低价购买和以较高价格出售的交易,“您不能在同一天进行买卖,必须先完成一项交易才能完成另一笔交易”,给定的示例[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
javascript arrays algorithm function output
1个回答
0
投票

在第2行(If语句)中,您使用了赋值运算符,而不是等号运算符。

由于k = 0,执行永远不会进入for循环“ for(let t = 1; t <= k; t ++)”]

 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);

0
投票

尝试一下:

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
   }

除了将利润值存储为数组外,什么都没有,因为您从未对数组执行任何操作

© www.soinside.com 2019 - 2024. All rights reserved.