Stock Buy Sell to Maximize Profit

Previous
Next

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

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

Algorithm:

Lets say we have array arr[] of stock prices.
We will track two variables :lowestPriceTillThatDay and 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:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog