Maximum difference between frequency of two elements such that element having greater frequency is also greater
Last Updated :
12 Feb, 2025
Given an array of n positive integers with many repeating elements. The task is to find the maximum difference between the frequency of any two different elements, such that the element with greater frequency is also greater in value than the second integer.
Examples:
Input : arr[] = { 3, 1, 3, 2, 3, 2 }.
Output : 2
Frequency of 3 = 3.
Frequency of 2 = 2.
Frequency of 1 = 1.
Here difference of frequency of element 3 and 1 is = 3 - 1 = 2.
Also 3 > 1.
Method 1 (Use Hashing): The naive approach can be, find the frequency of each element and for each element find the element having lesser value and lesser frequency than the current element.
Below is the implementation of this approach:
C++
// C++ program to find maximum difference
// between frequency of any two element
// such that element with greater frequency
// is also greater in value.
#include<bits/stdc++.h>
using namespace std;
// Return the maximum difference between
// frequencies of any two elements such that
// element with greater frequency is also
// greater in value.
int maxdiff(int arr[], int n)
{
unordered_map<int, int> freq;
// Finding the frequency of each element.
for (int i = 0; i < n; i++)
freq[arr[i]]++;
int ans = 0;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
// finding difference such that element
// having greater frequency is also
// greater in value.
if (freq[arr[i]] > freq[arr[j]] &&
arr[i] > arr[j] )
ans = max(ans, freq[arr[i]]-freq[arr[j]]);
else if (freq[arr[i]] < freq[arr[j]] &&
arr[i] < arr[j] )
ans = max(ans, freq[arr[j]]-freq[arr[i]]);
}
}
return ans;
}
// Driven Program
int main()
{
int arr[] = { 3, 1, 3, 2, 3, 2 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxdiff(arr, n) << endl;
return 0;
}
Java
// Java program to find maximum difference
// between frequency of any two element
// such that element with greater frequency
// is also greater in value.
import java.util.*;
class GFG
{
// Return the maximum difference between
// frequencies of any two elements such that
// element with greater frequency is also
// greater in value.
static int maxdiff(int arr[], int n)
{
Map<Integer, Integer> freq = new HashMap<>();
// Finding the frequency of each element.
for (int i = 0; i < n; i++)
freq.put(arr[i],
freq.get(arr[i]) == null ? 1 :
freq.get(arr[i]) + 1);
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// finding difference such that element
// having greater frequency is also
// greater in value.
if (freq.get(arr[i]) > freq.get(arr[j]) &&
arr[i] > arr[j])
ans = Math.max(ans, freq.get(arr[i]) -
freq.get(arr[j]));
else if (freq.get(arr[i]) < freq.get(arr[j]) &&
arr[i] < arr[j] )
ans = Math.max(ans, freq.get(arr[j]) -
freq.get(arr[i]));
}
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 3, 1, 3, 2, 3, 2 };
int n = arr.length;
System.out.println(maxdiff(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python
# Python program to find maximum difference
# between frequency of any two element
# such that element with greater frequency
# is also greater in value.
from collections import defaultdict
# Return the maximum difference between
# frequencies of any two elements such that
# element with greater frequency is also
# greater in value.
def maxdiff(arr, n):
freq = defaultdict(lambda: 0)
# Finding the frequency of each element.
for i in range(n):
freq[arr[i]] += 1
ans = 0
for i in range(n):
for j in range(n):
# finding difference such that element
# having greater frequency is also
# greater in value.
if freq[arr[i]] > freq[arr[j]] and arr[i] > arr[j]:
ans = max(ans, freq[arr[i]] - freq[arr[j]])
elif freq[arr[i]] < freq[arr[j]] and arr[i] < arr[j]:
ans = max(ans, freq[arr[j]] - freq[arr[i]])
return ans
arr = [3,1,3,2,3,2]
n = len(arr)
print(maxdiff(arr,n))
# This code is contributed by Shrikant13
C#
// C# program to find maximum difference
// between frequency of any two element
// such that element with greater frequency
// is also greater in value.
using System;
using System.Collections.Generic;
class GFG
{
// Return the maximum difference between
// frequencies of any two elements such that
// element with greater frequency is also
// greater in value.
static int maxdiff(int[] arr, int n)
{
Dictionary<int,
int> freq = new Dictionary<int,
int>();
// Finding the frequency of each element.
for (int i = 0; i < n; i++)
{
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq.Add(arr[i], 1);
}
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// finding difference such that element
// having greater frequency is also
// greater in value.
if (freq[arr[i]] > freq[arr[j]] && arr[i] > arr[j])
ans = Math.Max(ans, freq[arr[i]] - freq[arr[i]]);
else if (freq[arr[i]] < freq[arr[j]] && arr[i] < arr[j])
ans = Math.Max(ans, freq[arr[j]] - freq[arr[i]]);
}
}
return ans;
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 3, 1, 3, 2, 3, 2 };
int n = arr.Length;
Console.WriteLine(maxdiff(arr, n));
}
}
// This code is contributed by
// sanjeev2552
JavaScript
// JavaScript program to find maximum difference
// between frequency of any two elements
// such that the element with greater frequency
// is also greater in value.
function maxdiff(arr, n) {
let freq = new Map();
// Finding the frequency of each element.
for (let i = 0; i < n; i++)
freq.set(arr[i], freq.get(arr[i]) == null ? 1 : freq.get(arr[i]) + 1);
let ans = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
// Finding difference such that element
// having greater frequency is also greater in value.
if (freq.get(arr[i]) > freq.get(arr[j]) && arr[i] > arr[j])
ans = Math.max(ans, freq.get(arr[i]) - freq.get(arr[j]));
else if (freq.get(arr[i]) < freq.get(arr[j]) && arr[i] < arr[j])
ans = Math.max(ans, freq.get(arr[j]) - freq.get(arr[i]));
}
}
return ans;
}
// Driver code
let arr = [3, 1, 3, 2, 3, 2];
let n = arr.length;
console.log(maxdiff(arr, n));
Time Complexity: O(n2).
Auxiliary Space: O(n)
Method 2 (Use Hashing and Sorting): The idea is to find all the distinct elements and store them in an array, say dist[ ]. Sort the distinct element array dist[] in increasing order. Now for any distinct element at index i, for all index j such that i > j > 0, find the element between index 0 to i-1 having a minimum frequency. We can find the frequency of an element in the same way as method 1, i.e., storing frequencies in a hash table.
So do this for all i and find the maximum difference. To find the minimum frequency for all i maintain a prefix minimum.
Below is the representation of this approach:
C++
// Efficient C++ program to find maximum
// difference between frequency of any two
// elements such that element with greater
// frequency is also greater in value.
#include<bits/stdc++.h>
using namespace std;
// Return the maximum difference between
// frequencies of any two elements such that
// element with greater frequency is also
// greater in value.
int maxdiff(int arr[], int n)
{
unordered_map<int, int> freq;
int dist[n];
// Finding the frequency of each element.
int j = 0;
for (int i = 0; i < n; i++)
{
if (freq.find(arr[i]) == freq.end())
dist[j++] = arr[i];
freq[arr[i]]++;
}
// Sorting the distinct element
sort(dist, dist + j);
int min_freq = n+1;
// Iterate through all sorted distinct elements.
// For each distinct element, maintaining the
// element with minimum frequency than that
// element and also finding the maximum
// frequency difference
int ans = 0;
for (int i=0; i<j; i++)
{
int cur_freq = freq[dist[i]];
ans = max(ans, cur_freq - min_freq);
min_freq = min(min_freq, cur_freq);
}
return ans;
}
// Driven Program
int main()
{
int arr[] = { 3, 1, 3, 2, 3, 2 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxdiff(arr, n) << endl;
return 0;
}
Java
// Efficient Java program to find maximum
// difference between frequency of any two
// elements such that element with greater
// frequency is also greater in value.
import java.util.*;
class GFG
{
// Return the maximum difference between
// frequencies of any two elements such that
// element with greater frequency is also
// greater in value.
static int maxdiff(int arr[], int n)
{
HashMap<Integer,Integer> freq= new HashMap<>();
int []dist = new int[n];
// Finding the frequency of each element.
int j = 0;
for (int i = 0; i < n; i++)
{
dist[j++] = arr[i];
if (!freq.containsKey(arr[i]))
freq.put(arr[i], 1);
else
freq.put(arr[i], freq.get(arr[i]) + 1);
}
// Sorting the distinct element
Arrays.sort(dist);
int min_freq = n + 1;
// Iterate through all sorted distinct elements.
// For each distinct element, maintaining the
// element with minimum frequency than that
// element and also finding the maximum
// frequency difference
int ans = 0;
for (int i = 0; i < j; i++)
{
int cur_freq = freq.get(dist[i]);
ans = Math.max(ans, cur_freq - min_freq);
min_freq = Math.min(min_freq, cur_freq);
}
return ans;
}
// Driven Program
public static void main(String[] args)
{
int arr[] = { 3, 1, 3, 2, 3, 2 };
int n = arr.length;
System.out.print(maxdiff(arr, n) +"\n");
}
}
// This code is contributed by Rajput-Ji
Python
# Efficient Python3 program to find maximum
# difference between frequency of any two
# elements such that element with greater
# frequency is also greater in value.
# Return the maximum difference between
# frequencies of any two elements such that
# element with greater frequency is also
# greater in value.
def maxdiff(arr, n):
freq = {}
dist = [0] * n
# Finding the frequency of each element.
j = 0
for i in range(n):
if (arr[i] not in freq):
dist[j] = arr[i]
j += 1
freq[arr[i]] = 0
if (arr[i] in freq):
freq[arr[i]] += 1
dist = dist[:j]
# Sorting the distinct element
dist.sort()
min_freq = n + 1
# Iterate through all sorted distinct elements.
# For each distinct element, maintaining the
# element with minimum frequency than that
# element and also finding the maximum
# frequency difference
ans = 0
for i in range(j):
cur_freq = freq[dist[i]]
ans = max(ans, cur_freq - min_freq)
min_freq = min(min_freq, cur_freq)
return ans
# Driven Program
arr = [3, 1, 3, 2, 3, 2]
n = len(arr)
print(maxdiff(arr, n))
# This code is contributed by SHUBHAMSINGH10
C#
// Efficient C# program to find maximum
// difference between frequency of any two
// elements such that element with greater
// frequency is also greater in value.
using System.Collections.Generic;
using System;
class GFG{
// Return the maximum difference between
// frequencies of any two elements such
// that element with greater frequency
// is also greater in value.
static int maxdiff(int []arr, int n)
{
Dictionary<int,
int> freq = new Dictionary<int,
int>();
List<int> dist = new List<int>();
// Finding the frequency of each element.
int j = 0;
for(int i = 0; i < n; i++)
{
if (freq.ContainsKey(arr[i]) == false)
{
dist.Add(arr[i]);
j++;
}
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]]=1;
}
// Sorting the distinct element
dist.Sort();
int min_freq = n + 1;
// Iterate through all sorted distinct elements.
// For each distinct element, maintaining the
// element with minimum frequency than that
// element and also finding the maximum
// frequency difference
int ans = 0;
for(int i = 0; i < j; i++)
{
int cur_freq = freq[dist[i]];
ans = Math.Max(ans, cur_freq - min_freq);
min_freq = Math.Min(min_freq, cur_freq);
}
return ans;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 3, 1, 3, 2, 3, 2 };
int n = arr.Length;
Console.WriteLine(maxdiff(arr, n));
}
}
// This code is contributed by Stream_Cipher
JavaScript
// Efficient JavaScript program to find maximum
// difference between frequency of any two
// elements such that the element with greater
// frequency is also greater in value.
function maxdiff(arr, n) {
var freq = new Map();
var dist = Array(n);
// Finding the frequency of each element.
var j = 0;
for (var i = 0; i < n; i++) {
if (!freq.has(arr[i]))
dist[j++] = arr[i];
if (freq.has(arr[i]))
freq.set(arr[i], freq.get(arr[i]) + 1);
else
freq.set(arr[i], 1);
}
// Sorting the distinct elements
dist.sort((a, b) => a - b);
var min_freq = n + 1;
var ans = 0;
// Iterate through all sorted distinct elements.
for (var i = 0; i < j; i++) {
var cur_freq = freq.get(dist[i]);
ans = Math.max(ans, cur_freq - min_freq);
min_freq = Math.min(min_freq, cur_freq);
}
return ans;
}
// Driver Code
var arr = [3, 1, 3, 2, 3, 2];
var n = arr.length;
console.log(maxdiff(arr, n));
Time Complexity: O(n log n).
Auxiliary Space: O(n)
Similar Reads
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read