- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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
#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
- Related Articles
- Minimum operations required to make all the array elements equal in C++
- Minimum number of moves to make all elements equal using C++.
- Program to make all elements equal by performing given operation in Python
- Finding minimum steps to make array elements equal in JavaScript
- Minimum delete operations to make all elements of array same in C++.
- Minimum Moves to Equal Array Elements in C++
- Minimum operations of given type to make all elements of a matrix equal in C++
- Find the number of operations required to make all array elements Equal in C++
- Minimum move to end operations to make all strings equal in C++
- Number of operations required to make all array elements Equal in Python
- Minimum steps to make all the elements of the array divisible by 4 in C++
- Minimum number of operations on an array to make all elements 0 using C++.
- Minimum Moves to Equal Array Elements II in Python
- Minimum Swaps to Make Strings Equal in C++
- Minimizing array sum by applying XOR operation on all elements of the array in C++

Advertisements