Count Elements With Maximum Frequency - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2,3,3]
Output: 3
💡 Note: Element 3 appears 3 times (maximum frequency). Elements 1 and 2 appear 1 time each. Total frequency of elements with maximum frequency = 3.
Example 2 — Multiple Elements with Same Max Frequency
$ Input: nums = [1,1,2,2,3]
Output: 4
💡 Note: Elements 1 and 2 both appear 2 times (maximum frequency). Element 3 appears 1 time. Total frequency of elements with maximum frequency = 2 + 2 = 4.
Example 3 — All Elements Same Frequency
$ Input: nums = [1,2,3]
Output: 3
💡 Note: All elements appear 1 time (maximum frequency). Total frequency = 1 + 1 + 1 = 3.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Count Elements With Maximum Frequency INPUT nums = [1, 3, 2, 3, 3] 1 idx 0 3 idx 1 2 idx 2 3 idx 3 3 idx 4 Frequency Count: Element Frequency 1 1 2 1 3 3 (MAX) Red = Max frequency element Array length: 5 ALGORITHM STEPS Single-Pass Optimized 1 Initialize Variables maxFreq = 0, sumOfMax = 0 freqMap = {} 2 Count Frequencies For each num in array: freqMap[num]++ 3 Track Max in Single Pass If freq[num] > maxFreq: maxFreq = freq[num] sumOfMax = maxFreq 4 Handle Equal Max Else if freq[num] == maxFreq: sumOfMax += maxFreq Processing nums[4]=3: freq[3]=3 > maxFreq(2) maxFreq=3, sumOfMax=3 FINAL RESULT Maximum Frequency Found: maxFreq = 3 Elements with max frequency: Element: 3 Count: 3 times Total frequency sum: Output: 3 OK - Verified! Only element 3 has max freq Key Insight: The single-pass approach tracks both maximum frequency AND the sum of frequencies in one iteration. When a new max is found, reset sum. When equal to max, add to sum. Time: O(n), Space: O(n). TutorialsPoint - Count Elements With Maximum Frequency | Single-Pass Optimized
Asked in
Amazon 25 Google 18 Microsoft 15
12.5K Views
Medium Frequency
~8 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen