Skip to content

Commit aa22b49

Browse files
authored
Update 3005-count-elements-with-maximum-frequency.java
1 parent 05fdf23 commit aa22b49

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

Easy/3005-count-elements-with-maximum-frequency.java

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,18 @@
2020
Constraints:
2121
1 <= nums.length <= 100
2222
1 <= nums[i] <= 100
23+
*/
2324

24-
Approach:
25+
/*
26+
Approach 1 (HashMap):
2527
1. Count the frequency of each element using a HashMap.
2628
2. Find the maximum frequency among all elements.
2729
3. Sum the frequencies of elements that match this maximum.
2830
4. Return the result.
2931
30-
Time Complexity: O(n) where n = length of nums
32+
Time Complexity: O(n)
3133
Space Complexity: O(k) where k = number of distinct elements (at most 100)
3234
*/
33-
3435
class Solution {
3536
public int maxFrequencyElements(int[] nums) {
3637
HashMap<Integer, Integer> freq = new HashMap<>();
@@ -55,3 +56,36 @@ public int maxFrequencyElements(int[] nums) {
5556
return ans;
5657
}
5758
}
59+
60+
/*
61+
Approach 2 (Frequency Array):
62+
1. Since nums[i] <= 100, use an array of size 101 to count frequencies.
63+
2. Track the maximum frequency while counting.
64+
3. Sum the contributions of elements with maximum frequency.
65+
4. Return the result.
66+
67+
Time Complexity: O(n + k) (k = 100, treated as constant)
68+
Space Complexity: O(1) (fixed array of size 101)
69+
*/
70+
class SolutionArray {
71+
public int maxFrequencyElements(int[] nums) {
72+
int[] freqArr = new int[101];
73+
int maxFreq = 0;
74+
75+
// Step 1: count frequencies and track max
76+
for (int num : nums) {
77+
freqArr[num]++;
78+
maxFreq = Math.max(maxFreq, freqArr[num]);
79+
}
80+
81+
// Step 2: sum up contributions of max frequency
82+
int total = 0;
83+
for (int freq : freqArr) {
84+
if (freq == maxFreq) {
85+
total += freq;
86+
}
87+
}
88+
89+
return total;
90+
}
91+
}

0 commit comments

Comments
 (0)