Leetcode 3005. Count Elements With Maximum Frequency
You are given an integer array arr. Your task is to determine the number of elements in the array that appear with the maximum frequency.
0 since no elements exist in the array.unordered_map in C++) to count the frequency of each element in the array.Here is the C++ code to solve the problem:
#include <iostream>
#include <unordered_map>
#include <vector>
int countElementsWithMaximumFrequency(const std::vector<int>& arr) {
if (arr.empty()) {
return 0;
}
std::unordered_map<int, int> frequencyMap;
// Count the frequency of each element
for (const int &num : arr) {
frequencyMap[num]++;
}
// Find the maximum frequency
int maxFrequency = 0;
for (const auto &entry : frequencyMap) {
if (entry.second > maxFrequency) {
maxFrequency = entry.second;
}
}
// Count how many elements have this maximum frequency
int count = 0;
for (const auto &entry : frequencyMap) {
if (entry.second == maxFrequency) {
count++;
}
}
return count;
}
int main() {
std::vector<int> arr = {1, 3, 3, 1, 2, 4, 1};
std::cout << "Number of elements with maximum frequency: " << countElementsWithMaximumFrequency(arr) << std::endl;
return 0;
}
This solution reads the array, counts frequencies, identifies the highest frequency, and then counts how many elements have that frequency, all while maintaining excellent time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?