
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum delete operations to make all elements of array same in C++.
Problem statement
Given an array of n elements such that elements may repeat. We can delete any number of elements from array. The task is to find a minimum number of elements to be deleted from array to make it equal.
arr[] = {10, 8, 10, 7, 10, -1, -4, 12}
We have to delete highlighted 5 elements to make all array elements the same.
Algorithm
1. Count frequency of each element 2. Find maximum frequecy among the frequencies. Let us call this as maxFrequncy 3. Elements to be deleted: n – maxFrequecy where n is size of an array
Example
#include <iostream> #include <unordered_map> #include <climits> #define SIZE(arr) (sizeof(arr)/sizeof(arr[0])) using namespace std; int minDeleteOperations(int *arr, int n){ unordered_map<int, int> frequecy; int maxFrequency = INT_MIN; for (int i = 0; i < n; ++i) { frequecy[arr[i]]++; } for (auto it = frequecy.begin(); it != frequecy.end(); ++it) { maxFrequency = max(maxFrequency, it->second); } return (n - maxFrequency); } int main(){ int arr[] = {10, 8, 10, 7, 10, -1, 9, 4}; cout << "Required deletes: " << minDeleteOperations(arr, SIZE(arr)) << "\n"; return 0; }
Output
When you compile and execute the above program. It generates the following output −
Required deletes: 5
- Related Articles
- Minimum operations required to make all the array elements equal in C++
- Minimum number of operations required to delete all elements of the array using C++.
- Minimum number of operations on an array to make all elements 0 using C++.
- Minimum operations of given type to make all elements of a matrix equal in C++
- Minimum operation to make all elements equal in array in C++
- Minimum operations to make XOR of array zero in C++
- 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 operations required to set all elements of binary matrix in C++
- Minimum move to end operations to make all strings equal in C++
- Find minimum operations needed to make an Array beautiful in C++
- Minimum operations to make GCD of array a multiple of k in C++
- Minimum steps to make all the elements of the array divisible by 4 in C++
- Find minimum number of merge operations to make an array palindrome in C++
- C++ Program to count operations to make all gifts counts same

Advertisements