3005. Count Elements With Maximum Frequency #2204
-
Topics: You are given an array Return the total frequencies of elements in The frequency of an element is the number of occurrences of that element in the array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the total frequencies of elements in an array that have the maximum frequency. The frequency of an element is the number of times it appears in the array. The solution involves counting the occurrences of each element, identifying the maximum frequency, and then calculating the sum of the frequencies of all elements that have this maximum frequency. Approach
Let's implement this solution in PHP: 3005. Count Elements With Maximum Frequency <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxFrequencyElements($nums) {
$freqs = array_count_values($nums);
$maxFreq = max($freqs);
$count = 0;
foreach ($freqs as $f) {
if ($f == $maxFreq) {
$count++;
}
}
return $maxFreq * $count;
}
// Test cases
// Example 1
$nums1 = array(1, 2, 2, 3, 1, 4);
echo maxFrequencyElements($nums1) . "\n"; // Output: 4
// Example 2
$nums2 = array(1, 2, 3, 4, 5);
echo maxFrequencyElements($nums2) . "\n"; // Output: 5
?> Explanation:
This approach efficiently computes the desired result by leveraging basic array operations and a single pass through the frequency counts, ensuring optimal performance even for the upper constraint limits. The solution is straightforward and easy to understand, making it suitable for the problem's easy difficulty level. |
Beta Was this translation helpful? Give feedback.
We need to determine the total frequencies of elements in an array that have the maximum frequency. The frequency of an element is the number of times it appears in the array. The solution involves counting the occurrences of each element, identifying the maximum frequency, and then calculating the sum of the frequencies of all elements that have this maximum frequency.
Approach