Problem#
Example 1:#
Solution#
Method 1 – Hash Map for Counting#
Intuition#
To find the maximum number of students on a single bench, count the frequency of each bench number in the array. The answer is the highest frequency found.
Approach#
Use a hash map (dictionary) to count how many times each bench number appears in the array.
The answer is the maximum value in the hash map.
Code#
Cpp
Java
Python
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public :
int maximumStudents(vector< int >& benches) {
unordered_map< int , int > cnt;
int ans = 0 ;
for (int b : benches) {
ans = max(ans, ++ cnt[b]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maximumStudents (int [] benches) {
Map< Integer, Integer> cnt = new HashMap<> ();
int ans = 0;
for (int b : benches) {
cnt.put (b, cnt.getOrDefault (b, 0) + 1);
ans = Math.max (ans, cnt.get (b));
}
return ans;
}
}
1
2
3
4
5
class Solution :
def maximumStudents (self, benches: list[int]) -> int:
from collections import Counter
cnt = Counter(benches)
return max(cnt. values())
Complexity#
⏰ Time complexity: O(n)
, where n
is the number of students (length of benches array), since we count each bench once.
🧺 Space complexity: O(n)
, for the hash map storing counts.