
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
Maximum Equal Frequency in C++
Suppose we have an array nums of positive integers, we have to return the longest possible length of an array prefix of given array nums, such that it is possible to delete exactly one element from this prefix so that every number that has appeared in it will have the same frequency. After removing one element if there are no remaining elements, it's still considered that every appeared number has the same frequency (0).
So, if the input is like [3,3,2,2,6,4,4,6], then the output will be 7, So if we remove element 6 from index 4, then the subarray will be [3,3,2,2,4,4] where all elements appeared two times.
To solve this, we will follow these steps −
maxf := 0, res := 0
Define maps cnt and freq
-
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
x := nums[i]
(increase cnt[x] by 1)
f := cnt[x]
(increase freq[f] by 1)
decrease freq[f - 1] by 1
maxf := maximum of maxf and f
-
if maxf * freq[maxf] is same as i or (maxf - 1) * (freq[maxf - 1] + 1) is same as i or maxf is same as 1, then −
res := i + 1
return res
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxEqualFreq(vector<int>& nums) { int maxf = 0, res = 0; map<int, int> cnt, freq; for (int i = 0; i < nums.size(); i++) { int x = nums[i]; cnt[x]++; int f = cnt[x]; freq[f]++; freq[f - 1]--; maxf = max(maxf, f); if (maxf * freq[maxf] == i || (maxf - 1) * (freq[maxf - 1] + 1) == i || maxf == 1) { res = i + 1; } } return res; } }; main(){ Solution ob; vector<int> v = {3,3,2,2,6,4,4,6}; cout << (ob.maxEqualFreq(v)); }
Input
{3,3,2,2,6,4,4,6}
Output
7