使所有元素在C ++中的数组中相等的最小操作

问题陈述

给定一个具有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

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;

}

当您编译并执行上述程序时。它产生以下输出

输出结果

Minimum required operations = 3

以上是 使所有元素在C ++中的数组中相等的最小操作 的全部内容, 来源链接: utcz.com/z/335282.html

回到顶部