medium +25 pts

Maximum Average Pass Ratio

Use a max-heap of marginal gains to optimally distribute extra students among classes.

You are given an array `classes` where `classes[i] = [passi, totali]` indicates that in class `i` there are `passi` passing students out of `totali` total students. You are also given an integer `extraStudents`. You must assign the `extraStudents` students to the classes **one by one**; each time you add a student to a class, both the pass count and the total count of that class increase by 1. You may distribute the extra students among the classes in any order. Write a function `maxAverageRatio(classes, extraStudents)` that returns the **maximum** possible average pass ratio after all extra students are assigned. The average pass ratio is computed as `(1 / len(classes)) * sum(passi / totali)` after all assignments. Return the answer with an absolute error of at most `1e-5`. **Note:** It is always optimal to add the next extra student to the class with the largest **marginal gain** `(pass+1)/(total+1) - pass/total`. ### Function signature ```python def maxAverageRatio(classes: list[list[int]], extraStudents: int) -> float: ``` ### Constraints - `1 <= classes.length <= 10^5` - `1 <= passi <= totali <= 10^5` - `0 <= extraStudents <= 10^5` - The solution must run in `O((len(classes) + extraStudents) * log(len(classes)))` time and `O(len(classes))` space.

Constraints

- `1 <= classes.length <= 10^5` - `1 <= passi <= totali <= 10^5` - `0 <= extraStudents <= 10^5` - Expected time complexity: `O((classes.length + extraStudents) * log(classes.length))` - Expected space complexity: `O(classes.length)`

Example

```python
>>> maxAverageRatio([[1,2],[3,5],[2,2]], 2)
0.7833333333333333
>>> maxAverageRatio([[2,4],[3,9],[4,5],[2,10]], 4)
0.5348484848484849
>>> maxAverageRatio([[1,1],[1,1]], 5)
1.0
>>> maxAverageRatio([[1,1]], 0)
1.0
```
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

The marginal gain of adding a student to a class with (p, t) is `(p+1)/(t+1) - p/t`. This is always positive and decreases as the class improves.
Use a max-heap of `(-gain, p, t)` so the class with the largest current gain is popped first.
Repeat `extraStudents` times: pop the class with largest gain, increment p and t, recompute its gain, and push it back.
After all assignments, sum `p/t` over all classes and divide by the number of classes.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.