Cover image for LeetCode Daily Problem P3005 Count Elements With Maximum Frequency

LeetCode Daily Problem P3005 Count Elements With Maximum Frequency


Timeline

Timeline

2025-09-22

init

Counting sort

Problem:

This problem mainly uses array indices as element identifiers, and the array elements record frequencies.
The first traversal records the frequency of all elements, the second traversal finds the maximum frequency, and the third traversal sums all frequencies equal to the maximum. Overall complexity O(n).

1234567891011121314151617181920212223242526272829303132
#include <limits.h>#include <string.h>#include <vector>using std::vector;class Solution {    public:        // 1 <= nums[i] <= 100        int maxFrequencyElements(vector<int> &nums)        {                int n = nums.size();                int max = INT_MIN;                int res = 0;                int array[101];                memset(array, 0, 101 * sizeof(int));                for (int i = 0; i < n; i++) {                        array[nums[i]]++;                }                for (int i = 1; i < 101; i++) {                        if (array[i] > max) {                                max = array[i];                        }                }                for (int i = 1; i < 101; i++) {                        if (array[i] == max) {                                res += array[i];                        }                }                return res;        }};
Loading comments…