Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Solution: Count Elements With Maximum Frequency
Problem Statement
Given an array of positive integers named nums, return the total frequencies of the elements in nums that have a maximum frequency.
The frequency of an element is defined as the number of times that element is repeated in the array.
Examples
Example 1:
- Input: nums =
[3, 2, 2, 3, 1, 4] - Output: 4
- Explanation: Both 2 and 3 appear twice, which is the highest frequency. So, the total frequency is 2 + 2 = 4.
Example 2:
- Input: nums =
[5, 5, 5, 2, 2, 3] - Output: 3
.....
.....
.....
Like the course? Get enrolled and start learning!
Sachin Dev S
· 14 days ago
1 pass solution
import java.util.HashMap; public class Solution { public int countMaxFrequency(int[] nums) { Map<Integer, Integer> freqMap = new HashMap<>(); int maxFreq = 0; int count = 0; for(int num: nums) { int freq = freqMap.merge(num, 1, Integer::sum); if(freq > maxFreq) { maxFreq = freq; count = freq; } else if(freq == maxFreq) { count += freq; } } return count; } }
Show 1 reply
Reading Progress
0%