This solution finds max element, min element in given array with time complexity of O(n). But I still didn't figure out how to use fact that index of max is greater than index of min

public class FindMaxMin{

public static void main(String[] args){

int[] a = {1,3,5,22,15,34,2,674,56};

int min = findMin(a);//O(n)

int max = findMax(a);//O(n)

System.out.println("Max is "+max);

System.out.println("Min is "+min);

System.out.println("Maximum difference is "+max - min);

}

public static int findMax(int[] input){

for(int i = 0; i input[i+1]){

int temp = input[i];

input[i] = input[i+1];

input[i+1] = temp;

}

}

return input[input.length-1];

}

public static int findMin(int[] input){

for(int i = 0; i < input.length-1; i++){

if(input[i] < input[i+1]){

int temp = input[i];

input[i] = input[i+1];

input[i+1] = temp;

}

}

return input[input.length-1];

}

}

It could have been solved by traversing the array, maintaining min , its index and max and its index (maxindex > minindex) and returning difference.

I suggested a dynamic programming approach of storing the difference seen till now in a matrix..but I am not sure if it was correct.