Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The answer counts occurrences, not just distinct values. If several different numbers share the highest frequency, every occurrence of each of those numbers contributes.
Approach
Build a frequency map by scanning nums. Find the largest count in the map, then inspect the counts again. Add a count to the answer exactly when it equals that maximum.
The map groups all occurrences of each value together. Summing the maximum-frequency groups therefore includes every required array element once and excludes every less frequent value. For example, two distinct values each appearing three times contribute six elements, not two or three. The input is nonempty, so a maximum frequency always exists.
class Solution:
def maxFrequencyElements(self, nums: List[int]) -> int:
fm = defaultdict(int)
for n in nums:
fm[n] += 1
vals = fm.values()
mx = max(vals)
res = 0
for v in vals:
if v != mx:
continue
res += v
return resComplexity analysis
Let n = nums.length and u be the number of distinct values. Time: O(n + u). Auxiliary space: O(u).
