Maximum Average Pass Ratio Problem
Description
LeetCode Problem 1792.
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] = [pass_i, total_i]. You know beforehand that in the i^th class, there are total_i total students, but only pass_i 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 <= 10^5classes[i].length == 21 <= pass_i <= total_i <= 10^51 <= extraStudents <= 10^5
Solution
Approach: Max-Heap on the Gain
Adding one passing student to a class with a passes out of b students changes its ratio from a / b to (a + 1) / (b + 1). The gain shrinks as a class gets bigger, so giving each extra student to the class with the largest current gain is optimal.
Keep the classes in a max-heap ordered by that gain. Repeat extraStudents times: pop the best class, add one to both its passes and its students, and push it back. Finally average the ratios of all classes.
Complexity: time O((n + k) log n), space O(n), where n is the number of classes and k is extraStudents.
from heapq import heapify, heappop, heappush
class Solution:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
h = [(a / b - (a + 1) / (b + 1), a, b) for a, b in classes]
heapify(h)
for _ in range(extraStudents):
_, a, b = heappop(h)
a, b = a + 1, b + 1
heappush(h, (a / b - (a + 1) / (b + 1), a, b))
return sum(v[1] / v[2] for v in h) / len(classes)