Find maximum difference between two elements such that larger element appears after the smaller number in Java

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

 
int arr[]={14, 12, 70, 15, 95, 65, 22, 30};
Max Difference =95-12 = 83
public static int calculateMaxDifferenceBetweenTwoElements(int[] arr)
 {
 int minElementTillNow=arr[0];
 int maxDifference=Integer.MIN_VALUE;
 for (int i = 0; i < arr.length; i++) {
 int difference=0;
 if(arr[i] >minElementTillNow)
 {
 difference=arr[i]-minElementTillNow;
 if(difference > maxDifference)
 {
 maxDifference=difference;
 }
 }
 else
 {
 minElementTillNow=arr[i];
 }
 }
 return maxDifference;
 }
 

Leave a Comment