Count decrements to nearest smaller element required to make all array elements equal
Last Updated :
05 Aug, 2021
Given an array arr[] consisting of N non-negative integers, the task is to find the number of operations required to make all array elements equal. In each operation, any array element can be changed to its nearest smaller array element.
Examples:
Input: arr[] = {2, 5, 4, 3, 5, 4}
Output: 11
Explanation:
Step 1: Replace all 5s with 4s. Therefore, arr[] = {2, 4, 4, 3, 4, 4}. Count of operations = 2
Step 2: Replace all 4s with 3s. Therefore, arr[] = {2, 3, 3, 3, 3, 3}. Count of operations = 4
Steps 3: Replace all 3s with 2s. Therefore, arr[] = {2, 2, 2, 2, 2, 2}. Count of operations = 5
Therefore, total number of operations = 11
Input : arr[] = {2, 2, 2}
Output : 0
Approach: The idea is to use a sorting algorithm and a Map data structure. Follow the steps below to solve the problem:
- Initialize a Map to store the frequency of each array element except for the minimum element where keys (K) are the set of unique elements and values (V) are their frequencies.
- Sort the Map in decreasing order based on the keys.
- Initialize two variables ans and prev_val with 0 to store the current answer and the prefix sum respectively.
- Now iterate the Map and add the corresponding frequencies of each element along with prev_val to ans as ans = ans + (freq) + prev_val
- While iterating the Map, increment prev_val every time by the frequency of the current element.
- After traversing the Map completely, print ans as the minimum number of operations.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int MinimumNoOfOperations( int arr[], int n)
{
int min_ele = INT_MAX;
for ( int i = 0; i < n; ++i) {
min_ele = min(min_ele, arr[i]);
}
map< int , int , greater< int > > mp;
for ( int i = 0; i < n; ++i) {
if (arr[i] == min_ele)
continue ;
else
mp[arr[i]]++;
}
map< int , int >::iterator it;
int prev_val = 0;
int ans = 0;
for (it = mp.begin(); it != mp.end();
++it) {
ans += (it->second + prev_val);
prev_val += it->second;
}
return ans;
}
int main()
{
int arr[] = { 2, 5, 4, 3, 5, 4 };
int size = sizeof (arr)
/ sizeof (arr[0]);
cout << MinimumNoOfOperations(
arr, size);
return 0;
}
|
Java
import java.util.*;
class solution{
static int MinimumNoOfOperations( int arr[],
int n)
{
int min_ele = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; ++i)
{
min_ele = Math.min(min_ele,
arr[i]);
}
TreeMap<Integer,
Integer> mp =
new TreeMap<Integer,
Integer>(
Collections.reverseOrder());
for ( int i = 0 ; i < n; ++i)
{
if (arr[i] == min_ele)
continue ;
else
mp.put(arr[i],
mp.getOrDefault(arr[i], 0 ) + 1 );
}
int prev_val = 0 ;
int ans = 0 ;
for (Map.Entry<Integer,
Integer> it : mp.entrySet())
{
ans += (it.getValue() + prev_val);
prev_val += it.getValue();
}
return ans;
}
public static void main(String args[])
{
int arr[] = { 2 , 5 , 4 , 3 , 5 , 4 };
int size = arr.length;
System.out.println(
MinimumNoOfOperations(arr, size));
}
}
|
Python3
import sys
def MinimumNoOfOperations(arr, n):
min_ele = sys.maxsize
for i in range (n):
min_ele = min (min_ele, arr[i])
mp = {}
for i in range (n):
if (arr[i] = = min_ele):
continue
else :
mp[arr[i]] = mp.get(arr[i], 0 ) + 1
prev_val = 0
ans = 0
for it in mp:
ans + = (mp[it] + prev_val)
prev_val + = mp[it]
return ans
if __name__ = = '__main__' :
arr = [ 2 , 5 , 4 , 3 , 5 , 4 ]
size = len (arr)
print (MinimumNoOfOperations(arr, size))
|
C#
using System.Collections.Generic;
using System;
using System.Linq;
class GFG{
static int MinimumNoOfOperations( int []arr,
int n)
{
int min_ele = 1000000000;
for ( int i = 0; i < n; ++i)
{
min_ele = Math.Min(min_ele, arr[i]);
}
Dictionary< int ,
int > mp = new Dictionary< int ,
int >();
for ( int i = 0; i < n; ++i)
{
if (arr[i] == min_ele)
continue ;
else
{
if (mp.ContainsKey(arr[i]) == true )
mp[arr[i]] += 1;
else
mp[arr[i]] = 1;
}
}
int prev_val = 0;
int ans = 0;
var val = mp.Keys.ToList();
foreach ( var key in val)
{
ans += (mp[key] + prev_val);
prev_val += mp[key];
}
return ans;
}
public static void Main(String[] args)
{
int []arr = { 2, 5, 4, 3, 5, 4 };
int size = arr.Length;
Console.WriteLine(MinimumNoOfOperations(
arr, size));
}
}
|
Javascript
<script>
function MinimumNoOfOperations(arr, n)
{
var min_ele = 1000000000;
for ( var i = 0; i < n; ++i) {
min_ele = Math.min(min_ele, arr[i]);
}
var mp = new Map();
for ( var i = 0; i < n; ++i) {
if (arr[i] == min_ele)
continue ;
else
{
if (mp.has(arr[i]))
{
mp.set(arr[i], mp.get(arr[i])+1);
}
else
{
mp.set(arr[i], 1);
}
}
}
var prev_val = 0;
var ans = 0;
var keys = [];
mp.forEach((value, key) => {
keys.push(key);
});
keys.sort((a,b)=>b-a);
keys.forEach(value => {
ans += (mp.get(value) + prev_val);
prev_val += mp.get(value);
});
return ans;
}
var arr = [2, 5, 4, 3, 5, 4];
var size = arr.length
document.write( MinimumNoOfOperations(
arr, size));
</script>
|
Time Complexity: O(N) where N is the size of the array.
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...