# Minimum operation to make all elements equal in array in C++

## 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.

## Example

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.

## Algorithm

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

## Example

Live Demo

#include
using namespace std;
int getMinOperations(int *arr, int n) {
unordered_map hash;
for (int i = 0;i < n; ++i) {
hash[arr[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

## Output

Minimum required operations = 3

Updated on: 23-Dec-2019

2K+ Views

Get certified by completing the course