File tree Expand file tree Collapse file tree 1 file changed +37
-3
lines changed
Expand file tree Collapse file tree 1 file changed +37
-3
lines changed Original file line number Diff line number Diff line change 2020Constraints:
21211 <= nums.length <= 100
22221 <= nums[i] <= 100
23+ */
2324
24- Approach:
25+ /*
26+ Approach 1 (HashMap):
25271. Count the frequency of each element using a HashMap.
26282. Find the maximum frequency among all elements.
27293. Sum the frequencies of elements that match this maximum.
28304. Return the result.
2931
30- Time Complexity: O(n) where n = length of nums
32+ Time Complexity: O(n)
3133Space Complexity: O(k) where k = number of distinct elements (at most 100)
3234*/
33-
3435class 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+ }
You can’t perform that action at this time.
0 commit comments