Skip to content

← leetcode

Count Elements With Maximum Frequency

· Easy

LeetCode problem 3005

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 num is less than maxFreq
    • do nothing
  • the frequency of num is equal to maxFreq
    • we add maxFreq to ans (another element that shares the maxFreq)
  • the frequency of num is more than maxFreq
    • we have a new king; have to update maxFreq and ans (as there is now only 1 element with the maxFreq)
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) where n is the number of elements inside nums
  • Space: O(n)

time taken

  • 1 minute and 30 seconds