Get Maximum Difference Of Two Element In Array

This program calculate maximum difference between two  element of array
Example:

5,6,9,4,12,8,10,3,11

In this set of number
difference between 12 and 3 is maximum 9

public class max_diff_in_array {

public static void main(String[] args) {

int arr[]={5,6,9,4,12,8,10,3,11};
int max=0;
int x=0,y=0;
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {

int diff= Math.abs(arr[i]-arr[j]);
//System.out.println(diff);
if(max<diff)
{
max=diff;
x=i;
y=j;
}
}
}

System.out.println(“max=”+max+”x=”+arr[x]+”y=”+arr[y]);

}
}

2 comments

  1. You can also sort the array at first. Then try to subtract first and last element. In this way time complexity is the same as your sort algorithm

Leave a Reply

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

4 + 1 =