3005 - Count Elements With Maximum Frequency (Easy)
Problem Link
https://leetcode.com/problems/count-elements-with-maximum-frequency/
Problem Statement
You are given an array nums
consisting of positive integers.
Return the total frequencies of elements innums
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 <= 100
1 <= nums[i] <= 100
Approach 1: frequency count, get max, accumulate
The first approach is to do a frequency count first, then find the maximum frequency, and finally sum up all the frequency that are equal the the max.
Let be the number of elements of nums, then the
-
Time complexity is as nums could only have distinct elements and then we are doing 3 passes over the data, and the
-
Space comlexity is as the hash map could grow to the size of the input.
- C++
static int maxFrequencyElements(const vector<int>& nums) {
// frequency count
unordered_map<int, int> cnt;
for (int num : nums) ++cnt[num];
// find max count
int mx = 0;
for (auto [num, c] : cnt) mx = max(mx, c);
// sum up max counts
int ans = 0;
for (auto [num, c] : cnt)
if (c == mx) ans += c;
return ans;
}