Maximum Equal Frequency LeetCode solution in C++

1
class Solution {
2
public:
3
int maxEqualFreq(vector<int> &nums) {
4
int n = nums.size();
5
unordered_map<int, int> mp1,
6
mp2; // one to store the frequency of each number , and one which will
7
// store the frequency of the frequency
8
int ans = 0;
9
for (int i = 0; i < n; i++) {
10
int c = nums[i];
11
mp1[c]++;
12
mp2[mp1[c]]++;
13
if (i != n - 1 && mp2[mp1[c]] * mp1[c] == i + 1)
14
// when curernt length is equal to the total same frequency of numbers
15
// then we need one more number which may be anything so doesn't matter
16
// . so we just traverse till n-2 and that's it.
17

18
ans = i + 2;
19
if (mp2[mp1[c]] * mp1[c] == i)
20
// when current length is equal to the total same frequency of numbers
21
// plus one extra no. ( so here taken ==i (i+1-1)) which can be 1. same
22
// as any number present 2. different number .. but doesn't matter and
23
// our condition just satisfies ... so just take the current length .
24

25
ans = i + 1;
26
}
27
return ans;
28
}
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0