Find the maximum difference between two elements in the array such that smaller element appears before the larger element
import java.util.*;
public class MaxDiffElements {
public class Pair {
int min;
int max;
Pair(int min, int max){
this.min= min;
this.max = max;
}
public String toString() {
return "[" + min + "," + max + "]";
}
}
public static void main(String args[]) {
MaxDiffElements maxDiffElements = new MaxDiffElements();
int[][] input = {
null,
{},
{1},
{2,7,9,5,1,3,5},
{3,5,8,4,5,9,10,8,5,3,4},
{1,2,3,4,5},
{5,4,3,2,1}
};
for(int i=0; i< input.length; i++) {
System.out.println("Input: " + Arrays.toString(input[i]) + " Result: " + maxDiffElements.find(input[i]));
}
}
public Pair find(int[] input) {
if(input == null || input.length < 2 ) {
return null;
}
int maxSoFar = Integer.MIN_VALUE;
int diff = Integer.MIN_VALUE;
for(int i=input.length-1; i >=0; i--) {
if(input[i] > maxSoFar) {
maxSoFar = input[i];
}
if(maxSoFar - input[i] > diff) {
diff = maxSoFar - input[i];
}
}
return new Pair(maxSoFar-diff,maxSoFar);
}
}