Count Elements With Maximum Frequency
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.
nums = [1,2,2,3,1,4]4def 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;
}
Explanation
We need the combined size of every group that ties for the most occurrences. So first we have to know how often each distinct value appears, which is a classic frequency count with a hash map.
One pass over nums builds the map: for each value we bump its counter. After that, the largest counter value is the maximum frequency best.
Now comes the part people often get wrong: the answer is not the number of values tied for the max, it is the total elements they account for. If two different values each appear best times, they contribute best + best to the answer.
So we scan the frequency values once more and add up every frequency that equals best. Equivalently, the answer is best times the number of values achieving it — both produce the same sum.
Example: [1,2,2,3,1,4]. Counts are {1:2, 2:2, 3:1, 4:1}, so best = 2. Values 1 and 2 both hit it, contributing 2 + 2 = 4.