There is a simple one-pass solution.
First, keep track of the total frequencies of elements with max frequency, maximum frequency, and the frequencies of every element:
int totalFreq = 0;
int maxFreq = 0;
unordered_map<int, int> freq;
Then, iterate through nums.
For a given number, num, we have three cases:
- the frequency of
numis less thanmaxFreq- do nothing
- the frequency of
numis equal tomaxFreq- we add
maxFreqtoans(another element that shares themaxFreq)
- we add
- the frequency of
numis more thanmaxFreq- we have a new king; have to update
maxFreqandans(as there is now only 1 element with themaxFreq)
- we have a new king; have to update
for (int& num : nums) {
++freq[num];
if (freq[num] > maxFreq) {
maxFreq = totalFreq = freq[num];
} else if (freq[num] == maxFreq) {
totalFreq += freq[num];
}
}
Finally, we can simply return totalFreq. Now, I can finally work on my assignment-
return totalFreq;
code
class Solution {
public:
int maxFrequencyElements(vector<int>& nums) {
int totalFreq = 0;
int maxFreq = 0;
unordered_map<int, int> freq;
for (int& num : nums) {
++freq[num];
if (freq[num] > maxFreq) {
maxFreq = totalFreq = freq[num];
} else if (freq[num] == maxFreq) {
totalFreq += freq[num];
}
}
return totalFreq;
}
};
complexity
- Time:
O(n)wherenis the number of elements insidenums- Space:
O(n)
time taken
- 1 minute and 30 seconds