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

更新日期:2019 年 12 月 23 日

2K+ 瀏覽量

開啟您的職業

透過完成課程獲得認證

GET STARTED 開始
廣告