我编写了一个函数,可以从恰好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
答案 0 :(得分:0)
在第2行(If语句)中,您使用了赋值运算符,而不是等号运算符。
由于k = 0,执行永远不会进入for循环“ for(让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);
答案 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
}
除了将利润值存储为数组外,什么都没有,因为您从未对数组执行任何操作