Count Elements With Maximum Frequency - Hashmap [JS]

Description 

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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]