There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.
You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.
The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.
Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2
Output: 0.78333
Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
Example 2:
Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4
Output: 0.53485
Constraints:
- 1 <= classes.length <= 105
- classes[i].length == 2
- 1 <= passi <= totali <= 105
- 1 <= extraStudents <= 105
由于平均通过率是所有班级的通过率加和再除以班级的数量, 所以每个班级的通过率的增加量与最终结果都是成正比的, 我们需要做的就是每次找到增加一人所增加的通过率最大的那个班级添加一个人就可以了。
use std::collections::BinaryHeap;
impl Solution {
pub fn max_average_ratio(classes: Vec<Vec<i32>>, mut extra_students: i32) -> f64 {
let mut heap = BinaryHeap::new();
for c in classes {
heap.push((
// 增加一人所能增加的通过率
(c[0] as i64 + 1) * 100000000 / (c[1] as i64 + 1)
- c[0] as i64 * 100000000 / c[1] as i64,
c[0] as i64,
c[1] as i64,
));
}
while extra_students > 0 {
let (_, pass, total) = heap.pop().unwrap();
heap.push((
// 注意, 这里是下一次添加一人的通过率收益,所以是+2
(pass + 2) * 100000000 / (total + 2) - (pass + 1) * 100000000 / (total + 1),
pass + 1,
total + 1,
));
extra_students -= 1;
}
let len = heap.len() as f64;
heap.into_iter()
.map(|(_, pass, total)| pass as f64 / total as f64)
.sum::<f64>()
/ len
}
}

该问题涉及使用二叉堆策略为每个班级分配额外的学生,以最大限度地提高所有班级的平均通过率。通过计算每个班级增加一个学生后通过率的增益,并将额外学生分配给增益最大的班级,可以实现这一目标。算法首先将班级按通过率增益排序,然后依次分配学生。最终,计算新的平均通过率作为结果。
1150

被折叠的 条评论
为什么被折叠?



