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

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:

Add Comment