Skip to main contentprofolio

3005 — Count Elements With Maximum Frequency

Return the total number of elements that belong to the values with the highest frequency in an array.

Problem

Given an integer array nums, return the total number of elements that belong to the values with the highest frequency.

Example 1:

 Input: nums = [1,2,2,3,1,4]
  Output: 4
  Explanation:
  - 1 appears twice
  - 2 appears twice
  Maximum frequency = 2
  Total elements = 2 + 2 = 4

Example 2:

Input: nums = [1,2,3,4,5]
Output: 5
Explanation:
All numbers appear once. Maximum frequency = 1. Total = 5.

Approach

  1. Count the frequency of each number using a hashmap (Map in JavaScript).
  2. Find the maximum frequency.
  3. Add up all occurrences equal to this maximum.

Complexity

  • Time Complexity: O(n), where n is the length of nums.
  • Space Complexity: O(k), where k is the number of distinct values in nums.

JavaScript Solution

Java Solution


Insight

The answer is not the number of distinct values with maximum frequency, but the total number of elements belonging to them.


Source: