Maximum absolute difference between distinct elements in an Array

Given an array arr[] of N integers, the task is to find the maximum absolute difference between distinct elements of the array.

Examples:

Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}
Output: 10
Explanation:
Distinct elements of given array are 12, 9, 2.
Therefore, the maximum absolute difference between them is (12 – 2) = 10.

Input: arr[] = {2, -1, 10, 3, -2, -1, 10}
Output: 5
Explanation:
Distinct elements of given array are 2, 3, -2.
Therefore, the maximum absolute difference between them is (3 – (-2)) = 5.

Naive Approach: The naive approach is to store the distinct element in the given array in a array temp[] and print the difference of maximum and minimum element of the array temp[].



Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient Approach: The above naive approach can be optimized using Hashing. Below are the steps:

  1. Store the frequency of the each element of the array arr[] in an HashMap.
  2. Now find the maximum and minimum value of the array whose frequency is 1 using the above HashMap created.
  3. Print the difference of the maximum and minimum value obtained in the above step.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
  
class GFG {
  
    // Function to find the maximum
    // absolute difference between
    // distinct elements in arr[]
    static int MaxAbsDiff(int[] arr, int n)
    {
        // HashMap to store each element
        // with their occurrence in array
        Map<Integer, Integer> map
            = new HashMap<>();
  
        // maxElement and minElement to
        // store maximum and minimum
        // distinct element in arr[]
        int maxElement = Integer.MIN_VALUE;
        int minElement = Integer.MAX_VALUE;
  
        // Traverse arr[] and update each
        // element frequency in HashMap
        for (int i = 0; i < n; i++) {
            map.put(arr[i],
                    map.getOrDefault(arr[i], 0)
                        + 1);
        }
  
        // Traverse HashMap and check if
        // value of any key appears 1
        // then update maxElement and
        // minElement by that key
        for (Map.Entry<Integer, Integer> k :
             map.entrySet()) {
  
            if (k.getValue() == 1) {
                maxElement
                    = Math.max(maxElement,
                               k.getKey());
                minElement
                    = Math.min(minElement,
                               k.getKey());
            }
        }
  
        // Return absolute difference of
        // maxElement and minElement
        return Math.abs(maxElement
                        - minElement);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 12, 10, 9, 45, 2,
                      10, 10, 45, 10 };
        int n = arr.length;
  
        // Function Call
        System.out.println(MaxAbsDiff(arr, n));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to find the maximum
// absolute difference between
// distinct elements in []arr
static int MaxAbsDiff(int[] arr, int n)
{
      
    // Dictionary to store each element
    // with their occurrence in array
    Dictionary<int,
               int> map = new Dictionary<int,
                                         int>();
  
    // maxElement and minElement to
    // store maximum and minimum
    // distinct element in []arr
    int maxElement = int.MinValue;
    int minElement = int.MaxValue;
  
    // Traverse []arr and update each
    // element frequency in Dictionary
    for(int i = 0; i < n; i++)
    {
       if(map.ContainsKey(arr[i]))
          map[arr[i]] = map[arr[i]] + 1; 
       else
          map.Add(arr[i], 1);
    }
  
    // Traverse Dictionary and check if
    // value of any key appears 1
    // then update maxElement and
    // minElement by that key
    foreach (KeyValuePair<int, int> k in map)
    {
        if (k.Value == 1)
        {
            maxElement = Math.Max(maxElement, 
                                  k.Key);
            minElement = Math.Min(minElement,
                                  k.Key);
        }
    }
  
    // Return absolute difference of
    // maxElement and minElement
    return Math.Abs(maxElement - minElement);
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given array []arr
    int[] arr = { 12, 10, 9, 45, 2,
                  10, 10, 45, 10 };
    int n = arr.Length;
  
    // Function call
    Console.WriteLine(MaxAbsDiff(arr, n));
}
}
  
// This code is contributed by Princi Singh

chevron_right


Output:

10

Time Complexity: O(N)
Auxillary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princi singh