Home »
Java programming language
Java - Find maximum absolute difference in an array
Here, we are going to learn how to Java - Find maximum absolute difference in an array? How we can calculate maximum absolute difference in an array.
By Preeti Jain Last updated : February 03, 2024
Problem statement
Given an array, You have to write a Java program to find maximum absolute difference.
Approach
- In the first step, we take input an array with few elements.
int[] array = {10,20,50,80,90};
- In the second step, we will find the maximum and minimum element of an array.
- In the third step, we will subtract the minimum element from the maximum element of an array so the difference between the minimum and maximum element of an array is the maximum absolute difference of an array.
Java code to find maximum absolute difference in an array
// Java program to find the maximum absolute difference
// of an array
class MaximumAbsoluteDifferenceOfArray {
public static void main(String[] args) {
// Declare and initialize an array
int[] array = {
10,
20,
50,
80
};
int num_of_elements = array.length;
// To store the minimum and the maximum elements
// from the array and assigning first element
int min = array[0];
int max = array[0];
for (int i = 1; i < num_of_elements; i++) {
// We are comparing first element with all other elements
min = Math.min(min, array[i]);
max = Math.max(max, array[i]);
}
int abs_diff = max - min;
System.out.println("The maximum absolute difference of an array is " + abs_diff);
}
}
Output
The output of the above code is:
E:\Programs>javac MaximumAbsoluteDifferenceOfArray.java
E:\Programs>java MaximumAbsoluteDifferenceOfArray
The maximum absolute difference of an array is 70