给定一个具有n个正整数的数组。我们需要找到使所有元素相等的最小操作数。我们可以对数组元素上的任何元素执行加,乘,减或除运算。
如果输入数组= {1,2,3,4},那么我们需要最少3次操作才能使所有元素相等。例如,我们可以通过添加3个元素使元素4个。
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
#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) {
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;
}当您编译并执行上述程序时。它生成以下输出:
输出结果
Minimum required operations = 3