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!
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