Count Elements With Maximum Frequency - Hashmap [JS]
Solution: Hashmap
Store the counts of elements in a hashmap.
Keep track of the running max frequency.
If a count exceeds the max frequency, reset the total count.
If a count is equal to the max frequency, add to the total count.
Time Complexity: O(n)
Space Complexity: O(n)
var maxFrequencyElements = function(nums) {
let maxFreq = 0, countMap = {}, ans = 0;
for (let num of nums) {
countMap[num] = (countMap[num] || 0) + 1;
let count = countMap[num];
if (count > maxFreq) {
ans = count;
maxFreq = count;
} else if (count === maxFreq) {
ans += count;
}
}
return ans;
};
Comments
Post a Comment