
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Operations to Make All Array Elements Equal 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
#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; }
When you compile and execute above program. It generates following output:
Output
Minimum required operations = 3
Advertisements