You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

买卖股票的最佳时机:如何获取买入与卖出日的对应索引

算法调整方案

你原有的一次遍历O(n)复杂度的核心逻辑不需要改动,只需要额外新增几个变量记录价格对应的索引即可,调整后的代码如下:

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

const mainFunction = (pricesEachDay) => {
  // 边界情况处理:无法完成交易时返回对应值,可根据需求自行调整
  if (!pricesEachDay || pricesEachDay.length < 2) {
    return {
      maxProfit: 0,
      buyIndex: -1,
      sellIndex: -1
    }
  }
  let minPrice = pricesEachDay[0];
  let minPriceIndex = 0;
  let bestProfit = 0;
  let buyIndex = 0;
  let sellIndex = 0;

  for (let i = 1; i < pricesEachDay.length; i++) {
    const currentPrice = pricesEachDay[i];
    // 先更新当前遍历到的最低价格及对应索引
    if (currentPrice < minPrice) {
      minPrice = currentPrice;
      minPriceIndex = i;
    }
    // 计算当前利润,若超过历史最优则更新最优交易的索引和利润值
    const currentProfit = currentPrice - minPrice;
    if (currentProfit > bestProfit) {
      bestProfit = currentProfit;
      buyIndex = minPriceIndex;
      sellIndex = i;
    }
  }

  // 无盈利场景可自行调整返回的索引值,不需要高亮时返回-1即可
  return bestProfit > 0 ? {
    maxProfit: bestProfit,
    buyIndex,
    sellIndex
  } : {
    maxProfit: 0,
    buyIndex: -1,
    sellIndex: -1
  };
}

调用说明

用你给出的测试数组调用方法,返回结果为:
{ maxProfit: 7, buyIndex: 0, sellIndex: 3 }
你可以直接在React组件中拿到返回的buyIndex和sellIndex,和日期列表的索引匹配后添加高亮样式即可。

内容的提问来源于stack exchange,提问作者Miroslav Valkovič

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:18:00