Let’s consider the following situation. You’ve invited a lot of children to a celebration party, and you want to entertain them and also teach them something in the process. You are going to hire a few teachers and divide the children into groups and assign a teacher to each of the groups. This teacher will work with this group through the whole party.
But you know that for a teacher to work with a group of children efficiently children of that group should be of relatively the same age. More specifically age of any two children in the same group should differ by at most, one year.
Also, you want to minimize the number of groups. Because you want to hire fewer teachers, and spend the money on presents and other kinds of entertainment for the children. So, you need to divide children into the minimum possible number of groups. Such that the age of any two children in any group differs by at most one year.
Input: ages =[2.5,3.2,3.5,4.0,4.8,5.2,6.0]Output: 3 Explanation:- Group 1:[2.5,3.2,3.5]- Group 2:[4.0,4.8,5.2]- Group 3:[6.0] Minimum number of groups =3
Sort the Input: Sorting ensures that we attempt to group consecutive elements together.
Maintain a Group’s Upper Bound: Use a variable to track the maximum allowable age for the current group. If the next age exceeds this, start a new group.
Increment Group Counter: Every time a new group is started, increment the group counter.
classSolution {
funminGroups(ages: DoubleArray): Int {
ages.sort() // Step 1: Sort ages
var groups = 1var currentMax = ages[0] // First group's maximum age
for (age in ages) {
if (age > currentMax + 1.0) { // Step 2: Check if new group needed
groups++ currentMax = age
}
}
return groups
}
}
funmain() {
val solution = Solution()
val ages = doubleArrayOf(2.5, 3.2, 3.5, 4.0, 4.8, 5.2, 6.0)
println(solution.minGroups(ages)) // Output: 3
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defminGroups(self, ages):
ages.sort() # Step 1: Sort ages groups =1 current_max = ages[0] # First group's maximum agefor age in ages:
if age > current_max +1.0: # Step 2: Check if new group needed groups +=1 current_max = age
return groups
# Example usagesolution = Solution()
ages = [2.5, 3.2, 3.5, 4.0, 4.8, 5.2, 6.0]
print(solution.minGroups(ages)) # Output: 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fnmin_groups(mut ages: Vec<f64>) -> i32 {
ages.sort_by(|a, b| a.partial_cmp(b).unwrap()); // Step 1: Sort ages
letmut groups =1;
letmut current_max = ages[0]; // First group's maximum age
for&age in&ages {
if age > current_max +1.0 { // Step 2: Check if new group needed
groups +=1;
current_max = age;
}
}
groups
}
fnmain() {
let ages =vec![2.5, 3.2, 3.5, 4.0, 4.8, 5.2, 6.0];
println!("{}", min_groups(ages)); // Output: 3
}