【问题标题】:Best Time to Buy and Sell Stock - How to get index of Buy and Sell days [closed]买卖股票的最佳时间-如何获得买卖天数的指数[关闭]
【发布时间】:2021-11-29 16:02:20
【问题描述】:

我能够找到解决方案“找到最大利润的价值”。

  const pricesEachDay = [1,2,5,8,7,1,2,3]

  const mainFunction = (pricesEachDay) => {
  let buyPrice = pricesEachDay[0];
  let bestProfit = 0;

  for (const price of pricesEachDay) {
    const currentProfit = price - buyPrice;
    buyPrice = Math.min(buyPrice, price);
    bestProfit = Math.max(bestProfit, price - buyPrice);
  }

  return bestProfit;
}

我的问题是。我将如何处理它,如果我想找到我买入股票和卖出股票的那一天的指数,并将它与最大利润一起返还。所以我可以在 React 中突出显示它。 谢谢!

【问题讨论】:

  • 应该是“buyPrice”,抱歉打错了。已更正

标签: javascript arrays reactjs algorithm


【解决方案1】:

您可以将它们存储在局部变量中。

const pricesEachDay = [1,2,5,8,7,1,2,3]

const mainFunction = (pricesEachDay) => {
  let buyPrice = pricesEachDay[0];
  let bestProfit = 0;
  let boughtDay = 1;
  let lastPriceDay = 1;
  let soldDay = 1;
  let idx = 1;
  for (const price of pricesEachDay) {
    if(price < buyPrice) {
        buyPrice = price;
        lastPriceDay = idx;
    } 
    if(price - buyPrice > bestProfit) {
        bestProfit = price - buyPrice
        soldDay = idx;
        boughtDay = lastPriceDay;
    }
    idx++;
  }
  return [bestProfit, boughtDay, soldDay];
}

let arr = mainFunction(pricesEachDay)
console.log("Maximum profit: " + arr[0])
console.log("Day stock was bought: " + arr[1])
console.log("Day stock was sold: " + arr[2])

输出:

Maximum profit: 7
Day stock was bought: 1
Day stock was sold: 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2017-09-26
    • 2020-10-04
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多