[LeetCode] Count Elements With Maximum Frequency

3005. Count Elements With Maximum Frequency

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxFrequencyElements(vector<int>& nums) {
unordered_map<int, int> freq;
int ma = 0;
for(auto& x : nums) freq[x] += 1;
for(auto& [k,v] : freq) ma = max(ma,v);
int res = 0;
for(auto& [k,v] : freq) if(v == ma) res += 1;
return res * ma;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/01/14/PS/LeetCode/count-elements-with-maximum-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.