Stock Buy Sell to Maximize Profit

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

Given an array of integers representing stock price on a single day, find max profit that can be earned by 1 transaction.
So you need to find a pair (buyDay,sellDay) where buyDay < = sellDay and it should maximize the profit. For example:

Stock Buy Sell to Maximize Profit Algorithm

Lets say we have array arr[] of stock prices.
We will track two variables :lowestPriceTillThatDayand maxProfit.

  • lowestPriceTillThatDay will be initialise to arr[0].
  • Iterate over stock price array arr[]
  • If current element is greater than lowestPriceTillThatDay
    • calculate profit.
    • If profit is greater than maxProfit then update the maxProfit.
  • If current element is lesser than lowestPriceTillThatDay
    • update lowestPriceTillThatDay with current element.
  • We will get maxProfit in the end.

Java Program for Stock Buy Sell to Maximize Profit

When you run above program, you will get below output:

That’s all about Stock Buy Sell to Maximize Profit.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *