这是一个任务
假设你有一个数组价格,其中第i个元素是给定股票在第i天的价格。
设计一个算法来找到最大利润。你可以完成任意数量的交易(即多次购买一股股票并出售一股股票(。
注意:您不能同时进行多笔交易(即,您必须在再次购买之前出售股票(。
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
这是我对一个问题的解释和解释的解决方案,我知道有很多东西需要尝试理解
/**
* @param {number[]} prices
* @return {number}
*/
// already creating iterator to go through every element in array
var maxProfit = function(prices, i = 0, curSum = 0, maxSum = 0) {
if(i >= prices.length- 1) // exiting condition
return maxSum;
// to check array el. with every next possible number and create recursion to see if that's the maximum Profit
for(let j = i + 1; j < prices.length; ++j)
{
if(prices[j] - prices[i] > 0)
{
curSum += prices[j] - prices[i];
if(curSum > maxSum)
maxSum = curSum;
console.log('Im inside loop', curSum);
// here is an **error**, it works fine and even gives desired result **7**, but I don't know how and where it gives one more answer 9. By all my understanding it shouldn't. Can anybody explain where it gets 9?? I tried track it and console log it, but all in vain
maxProfit(prices, ++j, curSum, maxSum);
}
}
return maxProfit(prices, ++i, 0, maxSum);
};
让我们假设我们制作一个名为square的函数:
function square(a) {
return a * a;
}
然后,我们以与调用递归函数相同的方式在函数中使用它:
function test(b) {
square(b);
return b;
}
当调用它时,它只返回其参数:
test(5); // ==> 5
原因是从未使用square(b)
的结果。它进行了计算并返回给test
,但test
没有将该结果用于任何事情。如果square
有副作用,情况可能会有所不同,但没有,因此在test
中,square(b)
行是死代码。
在函数中,您调用maxProfit(prices, ++j, curSum, maxSum)
,并且从不将结果用于变量或返回它。因此,该行不会执行任何操作。所需的结果7
将被丢弃,因为您从未将其用于任何用途。
我想有些人会感到困惑,因为他们调用的函数与被调用者相同,但递归函数没有得到特殊处理。它们的工作原理与所有其他函数相同。他们等待,直到最终在每个级别返回结果,就好像他们调用了一个完全不同的函数来返回正确的答案一样。即使i
在递归调用中增加,当结果返回到第一个被调用者时,i
仍然为零。每个局部变量对于该调用都是唯一的,一个调用不会干扰另一个调用,除非你做了一些奇异的事情,比如全局状态或成员变量的突变。一个return
只后退一步。例如,即使square
返回,它也不会从test
返回。