Given an array arr[] of size N. The task is to make all the array elements equal by applying the below operations minimum number of times:
- Choose a pair of indices (i, j) such that |i – j| = 1 (indices i and j are adjacent) and set arr[i] = arr[i] + |arr[i] – arr[j]|
- Choose a pair of indices (i, j) such that |i – j| = 1 (indices i and j are adjacent) and set arr[i] = arr[i] – |arr[i] – arr[j]|
Examples:
Input: arr[] = { 2, 4, 6 }
Output: 2
Applying the 2nd type of operation on the given array gives {2, 2, 6}.
Now, applying 2nd type of operation again on the modified array gives {2, 2, 2}.
Input: arr[] = { 1, 1, 1}
Output: 0
All array elements are already equal.
Approach: Let’s find the most frequent element in the array (using map to store the frequencies of all the elements). Let this element be x. If we observe the operations more carefully, we can see that the part of these operations mean set element p to element q. If p < q then first operation needs to be performed, otherwise second.
Now, consider the number of operations in the optimal answer. It is obvious that we need at least n – freq(x) operations to equalize all the elements. And it is also obvious that we can always do it with n – freq(x) such operations which is the minimum number of operations required.
Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;
// Function to return the minimum operations // required to make all array elements equal int minOperations( int arr[], int n)
{ // To store the frequency
// of all the array elements
unordered_map< int , int > mp;
// Traverse through array elements and
// update frequencies
for ( int i = 0; i < n; i++)
mp[arr[i]]++;
// To store the maximum frequency
// of an element from the array
int maxFreq = INT_MIN;
// Traverse through the map and find
// the maximum frequency for any element
for ( auto x : mp)
maxFreq = max(maxFreq, x.second);
// Return the minimum operations required
return (n - maxFreq);
} // Driver code int main()
{ int arr[] = { 2, 4, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minOperations(arr, n);
return 0;
} |
// Java implementation of the above approach import java.util.*;
class GFG
{ // Function to return the minimum operations
// required to make all array elements equal
static int minOperations( int arr[], int n)
{
// To store the frequency
// of all the array elements
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
// Traverse through array elements and
// update frequencies
for ( int i = 0 ; i < n; i++)
{
if (mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1 );
}
else
{
mp.put(arr[i], 1 );
}
}
// To store the maximum frequency
// of an element from the array
int maxFreq = Integer.MIN_VALUE;
// Traverse through the map and find
// the maximum frequency for any element
maxFreq = Collections.max(mp.entrySet(),
Comparator.comparingInt(Map.Entry::getKey)).getValue();
// Return the minimum operations required
return (n - maxFreq);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 6 };
int n = arr.length;
System.out.println(minOperations(arr, n));
}
} /* This code contributed by PrinciRaj1992 */ |
# Python3 implementation of the approach import sys
# Function to return the minimum operations # required to make all array elements equal def minOperations(arr, n) :
# To store the frequency
# of all the array elements
mp = dict .fromkeys(arr, 0 );
# Traverse through array elements and
# update frequencies
for i in range (n) :
mp[arr[i]] + = 1 ;
# To store the maximum frequency
# of an element from the array
maxFreq = - (sys.maxsize - 1 );
# Traverse through the map and find
# the maximum frequency for any element
for key in mp :
maxFreq = max (maxFreq, mp[key]);
# Return the minimum operations required
return (n - maxFreq);
# Driver code if __name__ = = "__main__" :
arr = [ 2 , 4 , 6 ];
n = len (arr) ;
print (minOperations(arr, n));
# This code is contributed by Ryuga |
// C# implementation of the above approach using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{ // Function to return the minimum operations
// required to make all array elements equal
static int minOperations( int []arr, int n)
{
// To store the frequency
// of all the array elements
Dictionary< int , int > m = new Dictionary< int , int >();
// Traverse through array elements and
// update frequencies
for ( int i = 0; i < n; i++)
{
if (m.ContainsKey(arr[i]))
{
var val = m[arr[i]];
m.Remove(arr[i]);
m.Add(arr[i], val + 1);
}
else
{
m.Add(arr[i], 1);
}
}
// To store the maximum frequency
// of an element from the array
int maxFreq = int .MinValue;
// Traverse through the map and find
// the maximum frequency for any element
maxFreq = m.Values.Max();
// Return the minimum operations required
return (n - maxFreq);
}
// Driver code
public static void Main(String[] args)
{
int []arr = {2, 4, 6};
int n = arr.Length;
Console.WriteLine(minOperations(arr, n));
}
} // This code contributed by Rajput-Ji |
<script> // JavaScript implementation of the approach // Function to return the minimum operations // required to make all array elements equal function minOperations(arr, n) {
// To store the frequency
// of all the array elements
let mp = new Map();
// Traverse through array elements and
// update frequencies
for (let i = 0; i < n; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1)
} else {
mp.set(arr[i], 1)
}
}
// To store the maximum frequency
// of an element from the array
let maxFreq = Number.MIN_SAFE_INTEGER;
// Traverse through the map and find
// the maximum frequency for any element
for (let x of mp)
maxFreq = Math.max(maxFreq, x[1]);
// Return the minimum operations required
return (n - maxFreq);
} // Driver code let arr = [2, 4, 6]; let n = arr.length; document.write(minOperations(arr, n)); // This code is contributed by _saurabh_jaiswal </script> |
2
Time Complexity: O(N), where N represents the size of the given array.
Auxiliary Space: O(N), where N represents the size of the given array.