Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!