VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-absolute-difference-between-distinct-elements-in-an-array/

⇱ Maximum absolute difference between distinct elements in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum absolute difference between distinct elements in an Array

Last Updated : 15 Jul, 2025

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:
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 an 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 each element of the array arr[] in a 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 between the maximum and minimum value obtained in the above step.

Below is the implementation of the above approach:


Output: 
10

 

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

Comment
Article Tags: