Maximum difference between two elements such that larger element appears after the smaller number

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

Given array of integers, find Maximum difference between two elements such that larger element appears after the smaller number
For example:

Algorithm:

Lets say we have array arr[] of stock prices.
We will track two variable :minElementTillNow and maxDifference.

  • minElementTillNow will be initialise to arr[0].
  • Iterate over  arr[]
  • If current element is greater than minElementTillNow
    • calculate difference.
    • If difference is greater than maxDifference then update the maxDifference.
  • If current element is lesser than minElementTillNow
    • update minElementTillNow with current element.
  • We will get maxDifference in the end.

Java Program to find maximum difference between two elements :

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

Was this post helpful?

Leave a Reply

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