Count Elements With Maximum Frequency Problem
#3005
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3005.
You are given an array nums consisting 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.
Example 1:
Input: nums = [1,2,2,3,1,4]
Output: 4
Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 5
Explanation: All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Counting
Count how often each value occurs and find the maximum frequency mx. The answer is the total number of elements that belong to values with frequency mx, i.e. mx times the number of such values.
Complexity: O(n) time and O(n) space (O(1) with an array, since values are at most 100).
from collections import Counter
class Solution:
def maxFrequencyElements(self, nums: List[int]) -> int:
cnt = Counter(nums)
mx = max(cnt.values())
return sum(x for x in cnt.values() if x == mx)