Maximum absolute difference between distinct elements in an Array
Last Updated :
18 May, 2021
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 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:
- Store the frequency of each element of the array arr[] in a HashMap.
- Now find the maximum and minimum value of the array whose frequency is 1 using the above HashMap created.
- Print the difference between the maximum and minimum value obtained in the above step.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum
// absolute difference between
// distinct elements in arr[]
int MaxAbsDiff(int arr[], int n)
{
// Map to store each element
// with their occurrence in array
unordered_map<int, int> map;
// maxElement and minElement to
// store maximum and minimum
// distinct element in arr[]
int maxElement = INT_MIN;
int minElement = INT_MAX;
// Traverse arr[] and update each
// element frequency in Map
for(int i = 0; i < n; i++)
{
map[arr[i]]++;
}
// Traverse Map and check if
// value of any key appears 1
// then update maxElement and
// minElement by that key
for(auto itr = map.begin();
itr != map.end(); itr++)
{
if (itr -> second == 1)
{
maxElement = max(maxElement,
itr -> first);
minElement = min(minElement,
itr -> first);
}
}
// Return absolute difference of
// maxElement and minElement
return abs(maxElement - minElement);
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 12, 10, 9, 45, 2,
10, 10, 45, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << MaxAbsDiff(arr, n) << "\n";
return 0;
}
// This code is contributed by akhilsaini
Java
// 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));
}
}
Python3
# Python3 program for
# the above approach
import sys
from collections import defaultdict
# Function to find the maximum
# absolute difference between
# distinct elements in arr[]
def MaxAbsDiff(arr, n):
# HashMap to store each element
# with their occurrence in array
map = defaultdict (int)
# maxElement and minElement to
# store maximum and minimum
# distinct element in arr[]
maxElement = -sys.maxsize - 1
minElement = sys.maxsize
# Traverse arr[] and update each
# element frequency in HashMap
for i in range (n):
map[arr[i]] += 1
# Traverse HashMap and check if
# value of any key appears 1
# then update maxElement and
# minElement by that key
for k in map:
if (map[k] == 1):
maxElement = max(maxElement, k)
minElement = min(minElement, k)
# Return absolute difference of
# maxElement and minElement
return abs(maxElement - minElement)
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [12, 10, 9, 45, 2,
10, 10, 45, 10]
n = len( arr)
# Function Call
print(MaxAbsDiff(arr, n))
# This code is contributed by Chitranayal
C#
// 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
JavaScript
<script>
// Javascript program for the above approach
// Function to find the maximum
// absolute difference between
// distinct elements in arr[]
function MaxAbsDiff(arr, n)
{
// Map to store each element
// with their occurrence in array
var map = new Map();
// maxElement and minElement to
// store maximum and minimum
// distinct element in arr[]
var maxElement = -1000000000;
var minElement = 1000000000;
// Traverse arr[] and update each
// element frequency in Map
for(var i = 0; i < n; i++)
{
if(map.has(arr[i]))
map.set(arr[i], map.get(arr[i])+1)
else
map.set(arr[i], 1);
}
// Traverse Map and check if
// value of any key appears 1
// then update maxElement and
// minElement by that key
map.forEach((value, key) => {
if (value == 1)
{
maxElement = Math.max(maxElement,
key);
minElement = Math.min(minElement,
key);
}
});
// Return absolute difference of
// maxElement and minElement
return Math.abs(maxElement - minElement);
}
// Driver Code
// Given array arr[]
var arr = [12, 10, 9, 45, 2,
10, 10, 45, 10 ];
var n = arr.length;
// Function call
document.write( MaxAbsDiff(arr, n));
// This code is contributed by famously.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum difference between two elements in an Array Given an array arr[] of N integers, the task is to find the maximum difference between any two elements of the array.Examples: Input: arr[] = {2, 1, 5, 3} Output: 4 |5 - 1| = 4 Input: arr[] = {-10, 4, -9, -5} Output: 14 Naive Approach:- As the maximum difference will be in between smallest and the l
9 min read
Maximize sum of absolute difference between adjacent elements in Array with sum K Given two integers N and K, the task is to maximize the sum of absolute differences between adjacent elements of an array of length N and sum K. Examples: Input: N = 5, K = 10 Output: 20 Explanation: The array arr[] with sum 10 can be {0, 5, 0, 5, 0}, maximizing the sum of absolute difference of adj
4 min read
Maximum sum of absolute differences between distinct pairs of a triplet from an array Given an array arr[] consisting of N integers, the task is to find the maximum sum of absolute differences between all distinct pairs of the triplet in the array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6Explanation:The valid triplet is (1, 3, 4) as sum = |1 - 4| + |1 - 3| + |3 - 4| = 6, which
4 min read
Maximum difference between first and last indexes of an element in array Given an array of n integers. The task is to find the difference of first and last index of each distinct element so as to maximize the difference. Examples: Input : {2, 1, 3, 4, 2, 1, 5, 1, 7} Output : 6 Element 1 has its first index = 1 and last index = 7 Difference = 7 - 1 = 6 Other elements have
6 min read
Maximize the absolute difference for all elements in the array Given an array A[] of size N and B[] of size M (M >= N), the task is to construct an array C[] by choosing N integers from B[] such that for every index i, sum of absolute difference between A[i] and C[i] is maximum. Examples: Input: N = 4, M = 6, A[] = {6, 1, 2, 4}, B[] = {3, 5, 1, 7, 2, 3}Outpu
10 min read
Absolute Difference of all pairwise consecutive elements in an array Given an array of integers of N elements. The task is to print the absolute difference of all of the pairwise consecutive elements. Pairwise consecutive pairs of an array of size N are (a[i], a[i+1]) for all i ranging from 0 to N-2 Examples: Input: arr[] = {8, 5, 4, 3, 15, 20}Output: 3, 1, 1, 12, 5I
4 min read
Maximum difference between group of k-elements and rest of the array. You are given an array of n elements. You have to divide the given array into two group such that one group consists exactly k elements and second group consists rest of elements. Your result must be maximum possible difference of sum of elements of these two group. Examples: Input : arr[n] = {1, 5,
7 min read
k-th smallest absolute difference of two elements in an array We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] - a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) as the smallest absolute difference among all these pairs. Examples:
9 min read
Find minimum difference between any two elements (pair) in given array Given an unsorted array, find the minimum difference between any pair in the given array. Examples : Input: {1, 5, 3, 19, 18, 25}Output: 1Explanation: Minimum difference is between 18 and 19 Input: {30, 5, 20, 9}Output: 4Explanation: Minimum difference is between 5 and 9 Input: {1, 19, -4, 31, 38, 2
15+ min read
Array element with minimum sum of absolute differences | Set 2 Given an array arr[] consisting of N positive integers, the task is to find an array element X such that sum of its absolute differences with every array element is minimum. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 3Explanation: For element arr[0](= 1): |(1 - 1)| + |(2 - 1)| + |(3 - 1)| + |(4
7 min read