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]);
}
}
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]);
}
}
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
ReplyDeleteWhy not just iterate once to find max and min then calculate the diff? It is O(n) instead O(n 2) or O(nlogn)
ReplyDelete