Input: nums =[1,2,2,3,1,4]Output: 4Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.So the number of elements in the array with maximum frequency is4.
Input: nums =[1,2,3,4,5]Output: 5Explanation: All elements of the array have a frequency of 1 which is the maximum.So the number of elements in the array with maximum frequency is5.
classSolution {
publicintmaxFrequencyElements(int[] nums) {
Map<Integer, Integer> cnt =new HashMap<>();
int mx = 0, ans = 0;
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
for (int v : cnt.values()) mx = Math.max(mx, v);
for (int v : cnt.values()) if (v == mx) ans += v;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaxFrequencyElements(nums: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
var mx = 0var ans = 0for (x in nums) cnt[x] = cnt.getOrDefault(x, 0) + 1for (v in cnt.values) mx = maxOf(mx, v)
for (v in cnt.values) if (v == mx) ans += v
return ans
}
}
1
2
3
4
5
6
classSolution:
defmaxFrequencyElements(self, nums: list[int]) -> int:
from collections import Counter
cnt = Counter(nums)
mx = max(cnt.values())
return sum(v for v in cnt.values() if v == mx)
1
2
3
4
5
6
7
8
9
use std::collections::HashMap;
impl Solution {
pubfnmax_frequency_elements(nums: Vec<i32>) -> i32 {
letmut cnt = HashMap::new();
for&x in&nums { *cnt.entry(x).or_insert(0) +=1; }
let mx =*cnt.values().max().unwrap();
cnt.values().filter(|&&v| v == mx).map(|&v| v).sum()
}
}