Reduce Array Size to The Half in C++

Suppose we have an array arr. We can choose a set of integers and remove all the occurrences of these integers in the array. We have to find the minimum size of the set so that at least half of the integers of the array are removed. So for example, if arr = [3,3,3,3,5,5,5,2,2,7], then the output will be 2. This is because if we choose {3,7} this will make the new array [5,5,5,2,2] which has size 5 (this is equal to half of the size of the old array). Possible sets of size 2 are {3,5},{3,2},{5,2}. Selecting set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.

To solve this, we will follow these steps −

• Define a map m, n := size of arr, store the frequency of each element present in arr into map m

• define an array called temp, sz := n, and ret := 0

• for each key-value pair it in m

• insert the value of it into temp

• sort the temp array

• for I in range 0 to the size of temp

• if sz <= n / 2, then break from loop

• increase ret by 1

• decrease sz by temp[i]

• return ret

Example (C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minSetSize(vector<int>& arr) {
unordered_map <int, int> m;
int n = arr.size();
for(int i = 0; i < n; i++){
m[arr[i]]++;
}
vector <int> temp;
unordered_map <int, int> :: iterator it = m.begin();
int sz = n;
int ret = 0;
while(it != m.end()){
temp.push_back(it->second);
it++;
}
sort(temp.rbegin(), temp.rend());
for(int i = 0; i < temp.size(); i++){
if(sz <= n / 2)break;
ret++;
sz -= temp[i];
}
return ret;
}
};
main(){
vector<int> v = {3,3,3,3,5,5,5,2,2,7};
Solution ob;
cout << (ob.minSetSize(v));
}

Input

[3,3,3,3,5,5,5,2,2,7]

Output

2

Advertisements