Created
September 22, 2025 16:53
-
-
Save tatsuyax25/9c760b3124a33e69dd74cb632707b929 to your computer and use it in GitHub Desktop.
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 a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| */ | |
| var maxFrequencyElements = function(nums) { | |
| // Create an empty object to store the frequency of each number. | |
| const map = {}; | |
| // Initialize the maximum frequency to 0. | |
| let maxF = 0; | |
| // Iterate through the input array. | |
| for (let i = 0; i < nums.length; i++) { | |
| // If the number is not in the map, set its frequency to 1; otherwise, increment it. | |
| map[nums[i]] = map[nums[i]] === undefined ? 1 : map[nums[i]] + 1; | |
| // Update the maximum frequency if needed. | |
| maxF = maxF < map[nums[i]] ? map[nums[i]] : maxF; | |
| } | |
| // Initialize a variable to keep track of the total occurrences. | |
| let occurrences = 0; | |
| // Get an array of all frequency values. | |
| const values = Object.values(map); | |
| // Iterate through the frequency values. | |
| for (let i = 0; i < values.length; i++) { | |
| // If the frequency matches the maximum frequency, add it to the total occurrences. | |
| if (values[i] === maxF) { | |
| occurrences += values[i]; | |
| } | |
| } | |
| // Return the total occurrences. | |
| return occurrences; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment