You are given an array nums consisting of positive integers.
Return the total frequencies of elements innumssuch 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 <= 100
1 <= nums[i] <= 100
Solutions
Solution 1: Counting
Thinking
\(n \le 100\), so counting frequencies and summing is enough. The required quantity is the sum of those maximum frequencies, not the number of distinct values that attain them.
After the counts are known we take \(\textit{mx}\) and add every count equal to \(\textit{mx}\).
One counting pass and one scan of the values suffice.
We can use a hash table or array \(cnt\) to record the occurrence of each element.
Then we traverse \(cnt\) to find the element with the most occurrences, and let its occurrence be \(mx\). We sum up the occurrences of elements that appear \(mx\) times, which is the answer.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the array \(nums\).