Skip to content

Commit 22b7aaa

Browse files
authored
Create 3005-count-elements-with-maximum-frequency.java
1 parent ea16a78 commit 22b7aaa

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
https://leetcode.com/problems/count-elements-with-maximum-frequency/
3+
3005. Count Elements With Maximum Frequency
4+
5+
You are given an array nums consisting of positive integers.
6+
Return the total frequencies of elements in nums such that those elements all have the maximum frequency.
7+
8+
Example 1:
9+
Input: nums = [1,2,2,3,1,4]
10+
Output: 4
11+
Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
12+
So the number of elements in the array with maximum frequency is 4.
13+
14+
Example 2:
15+
Input: nums = [1,2,3,4,5]
16+
Output: 5
17+
Explanation: All elements of the array have a frequency of 1 which is the maximum.
18+
So the number of elements in the array with maximum frequency is 5.
19+
20+
Constraints:
21+
1 <= nums.length <= 100
22+
1 <= nums[i] <= 100
23+
24+
Approach:
25+
1. Count the frequency of each element using a HashMap.
26+
2. Find the maximum frequency among all elements.
27+
3. Sum the frequencies of elements that match this maximum.
28+
4. Return the result.
29+
30+
Time Complexity: O(n) where n = length of nums
31+
Space Complexity: O(k) where k = number of distinct elements (at most 100)
32+
*/
33+
34+
class Solution {
35+
public int maxFrequencyElements(int[] nums) {
36+
HashMap<Integer, Integer> freq = new HashMap<>();
37+
38+
// Step 1: count frequencies
39+
for (int num : nums) {
40+
freq.put(num, freq.getOrDefault(num, 0) + 1);
41+
}
42+
43+
// Step 2: find maximum frequency
44+
int max = 0;
45+
for (int val : freq.values()) {
46+
max = Math.max(max, val);
47+
}
48+
49+
// Step 3: sum up frequencies of elements with maximum frequency
50+
int ans = 0;
51+
for (int val : freq.values()) {
52+
if (val == max) ans += val;
53+
}
54+
55+
return ans;
56+
}
57+
}

0 commit comments

Comments
 (0)