Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
Best Time to Buy and Sell Stock - How to get index of Buy and Sell days

I was able to find solution "Find value of max profit".

  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;
}

My Question is. How would i approach it, if i wanted to find indexes of both day i bought stock and day i sell and return it along with max profit. So i can highlight it in React. Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can store them in local variables.

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])

Output:

Maximum profit: 7
Day stock was bought: 1
Day stock was sold: 4
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda