Problem
Given an integer array nums, return the total number of elements that belong to the values with the highest frequency.
Example 1:
Input: nums = [1,2,2,3,1,4] Output: 4 Explanation: - 1 appears twice - 2 appears twice Maximum frequency = 2 Total elements = 2 + 2 = 4
Example 2:
Input: nums = [1,2,3,4,5] Output: 5 Explanation: All numbers appear once. Maximum frequency = 1. Total = 5.
Approach
- Count the frequency of each number using a hashmap (Map in JavaScript).
- Find the maximum frequency.
- Add up all occurrences equal to this maximum.
Complexity
- Time Complexity: O(n), where n is the length of nums.
- Space Complexity: O(k), where k is the number of distinct values in nums.
JavaScript Solution
Java Solution
Insight
The answer is not the number of distinct values with maximum frequency, but the total number of elements belonging to them.
Source: