Count Elements With Maximum Frequency

easy array hash map counting

Problem

You are given an array nums of positive integers. Return the total frequencies of elements in nums such that those elements all have the maximum frequency. The frequency of an element is the number of occurrences of that element in the array.

Inputnums = [1,2,2,3,1,4]
Output4
1 and 2 each occur twice (the max frequency); they contribute 2 + 2 = 4 elements.

def max_frequency_elements(nums):
    freq = {}
    for x in nums:
        freq[x] = freq.get(x, 0) + 1
    best = max(freq.values())
    total = 0
    for f in freq.values():
        if f == best:
            total += f
    return total
function maxFrequencyElements(nums) {
  const freq = new Map();
  for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
  const best = Math.max(...freq.values());
  let total = 0;
  for (const f of freq.values()) {
    if (f === best) total += f;
  }
  return total;
}
class Solution {
    public int maxFrequencyElements(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int x : nums) freq.merge(x, 1, Integer::sum);
        int best = 0;
        for (int f : freq.values()) best = Math.max(best, f);
        int total = 0;
        for (int f : freq.values()) {
            if (f == best) total += f;
        }
        return total;
    }
}
int maxFrequencyElements(vector<int>& nums) {
    unordered_map<int, int> freq;
    for (int x : nums) freq[x]++;
    int best = 0;
    for (auto& p : freq) best = max(best, p.second);
    int total = 0;
    for (auto& p : freq) {
        if (p.second == best) total += p.second;
    }
    return total;
}
Time: O(n) Space: O(n)