

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 required to make all the 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
- Related Questions & Answers
- Find the number of operations required to make all array elements Equal in C++
- Number of operations required to make all array elements Equal in Python
- Minimum operation to make all elements equal in array in C++
- Minimum number of operations required to delete all elements of the array using C++.
- Minimum delete operations to make all elements of array same in C++.
- Minimum number of given operations required to make two strings equal using C++.
- Minimum operations of given type to make all elements of a matrix equal in C++
- Minimum move to end operations to make all strings equal in C++
- Minimum operations required to set all elements of binary matrix in C++
- Minimum number of operations on an array to make all elements 0 using C++.
- Minimum number of moves to make all elements equal using C++.
- Minimum operations required to remove an array in C++
- Program to find minimum operations to make array equal using Python
- Finding minimum steps to make array elements equal in JavaScript
- Minimum Moves to Equal Array Elements in C++
Advertisements