Minimum operations required to make all the array elements equal in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array with n positive integers. We need to find the minimum number of operation to make all elements equal. We can perform addition, multiplication, subtraction or division with any element on an array element.


If input array is = {1, 2, 3, 4} then we require minimum 3 operations to make all elements equal. For example, we can make elements 4 by doing 3 additions.


1. Select element with maximum frequency. Let us call it ‘x’ 
2. Now we have to perform n-x operations as there are x element with same value


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinOperations(int *arr, int n) {
   unordered_map<int, int> hash;
   for (int i = 0;i < n; ++i) {
int maxFrequency = 0;
   for (auto elem : hash) {
      if (elem.second > maxFrequency) {
         maxFrequency = elem.second;
   return (n - maxFrequency);
int main() {
   int arr[] = {1, 2, 3, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum required operations = " <<
   getMinOperations(arr, n) << endl;
   return 0;

When you compile and execute above program. It generates following output:


Minimum required operations = 3
Published on 23-Dec-2019 10:00:56