Home » Java programming language

Find maximum absolute difference in an array

Here, we are going to learn how to find maximum absolute difference in an array? How we can calculate maximum absolute difference in an array?
Submitted by Preeti Jain, on July 16, 2019

Given an array and we have to find maximum absolute difference.

Approach to follow:

  • 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.

Example:

// 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

E:\Programs>javac MaximumAbsoluteDifferenceOfArray.java

E:\Programs>java MaximumAbsoluteDifferenceOfArray
The maximum absolute difference of an array is 70





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.