Pude encontrar la solución "Encontrar el valor de la ganancia máxima".
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; }Mi pregunta es. ¿Cómo lo abordaría si quisiera encontrar índices tanto del día en que compré acciones como del día en que vendí y devolverlos junto con la ganancia máxima? Entonces puedo resaltarlo en React. ¡Gracias!
Puede almacenarlos en variables locales.
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])Producción:
Maximum profit: 7 Day stock was bought: 1 Day stock was sold: 4