在 for 循环中计算最大值 - 最小值

时间:2021-01-12 02:35:57

标签: javascript

我尝试做这个练习,其中的想法是,从一系列股票价值中,以较低的价值买入并以较高的价值卖出。

示例:

Input: [7,1,5,3,6,4]
Output: 5

说明:

在第 2 天买入(价格 = 1)并在第 5 天卖出(价格 = 6),利润 = 6-1 = 5。

不是 7-1 = 6,因为卖价需要大于买价。

我试图了解 for 循环在我发现的这个解决方案中是如何工作的:

var maxProfit = function(prices) {
  let profit = 0;
  let min =  Number.MAX_SAFE_INTEGER;
 
  for(let i = 0; i < prices.length; i++) {

    min = Math.min(min, prices[i]);
    profit = Math.max(profit, prices[i] - min);
  }    

  return profit
}

有以下数组 [7,1,5,3,6,4],我知道:

min = Math.min(min, prices[i]);  = 1

但我不明白为什么这一行:profit = Math.max(profit, prices[i] - min); 知道在找到最小值 6-1 后只减去数组的较高值

当我输入 min 变量返回的数字 1 时,像这样:profit = Math.max(profit, prices[i] - 1); 它转到数组的开头并执行 7-1。

我希望我的问题有意义。我对循环在这里的运行方式感到非常困惑。

谢谢

3 个答案:

答案 0 :(得分:0)

profit = 0; //init
profit = Math.Max(0,7-7)//i=0; profit = 0
profit = Math.Max(0,1-1)//i=1; profit = 0
profit = Math.Max(0,5-1)//i=2; profit = 4
profit = Math.Max(4,3-1)//i=3; profit = 4
profit = Math.Max(4,6-1)//i=4; profit = 5
profit = Math.Max(5,4-1)//i=5; profit = 5

答案 1 :(得分:-2)

我认为您真的希望这样做:

function maxProfit(prices, startDay = 1){
  const p = prices.slice(startDay-1);
  return Math.max(...p)-Math.min(...p);
}
const nums = [7, 1, 5, 3, 6, 4];
console.log(maxProfit(nums, 2));

当然,我个人会在第一天使用零索引,但这就是您想要的......我想。

答案 2 :(得分:-2)

阅读有关 console.log 和调试的信息。

这个:

min = Math.min(min, prices[i]);

不等于1,它取决于iminprices数组。 >

分析以下脚本的输出:

var maxProfit = function(prices) {
  let profit = 0;
  let min =  Number.MAX_SAFE_INTEGER;
 
  for(let i = 0; i < prices.length; i++) {

    min = Math.min(min, prices[i]);
    profit = Math.max(profit, prices[i] - min);
    console.log("i: ", i, " price: ", prices[i], " min: ", min, " profit: ", profit);
  }    

  return profit
}

var prices = [7,1,5,3,6,4];

maxProfit(prices);

相关问题