【发布时间】:2020-05-18 21:33:54
【问题描述】:
我写了一个函数来找出恰好 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
【问题讨论】:
-
请修正缩进
-
您永远不会更新
profit数组。您只能潜在地覆盖变量,但永远不会向数组本身添加任何内容。
标签: javascript arrays algorithm function output