1792. Maximum Average Pass Ratio #957
-
Topics: 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 You are also given an integer 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 Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a max-heap (priority queue). This is because we need to efficiently find the class that benefits the most (maximizes the change in pass ratio) when adding an extra student. Approach:
Let's implement this solution in PHP: 1792. Maximum Average Pass Ratio <?php
/**
* @param Integer[][] $classes
* @param Integer $extraStudents
* @return Float
*/
function maxAverageRatio($classes, $extraStudents) {
// Create a max-heap using a priority queue
$maxHeap = new SplPriorityQueue();
// Populate the heap with the classes and their extra pass ratio
foreach ($classes as $class) {
list($pass, $total) = $class;
$extraRatio = extraPassRatio($pass, $total);
$maxHeap->insert([$pass, $total], $extraRatio);
}
// Distribute the extra students
for ($i = 0; $i < $extraStudents; ++$i) {
list($pass, $total) = $maxHeap->extract();
$pass += 1;
$total += 1;
$extraRatio = extraPassRatio($pass, $total);
$maxHeap->insert([$pass, $total], $extraRatio);
}
// Calculate the average pass ratio
$totalRatio = 0;
$count = count($classes);
while (!$maxHeap->isEmpty()) {
list($pass, $total) = $maxHeap->extract();
$totalRatio += $pass / $total;
}
return $totalRatio / $count;
}
/**
* Calculate the extra pass ratio when a student is added to the class
*
* @param $pass
* @param $total
* @return float|int
*/
private function extraPassRatio($pass, $total)
{
return ($pass + 1) / ($total + 1) - $pass / $total;
}
// Example usage:
$classes = [[1, 2], [3, 5], [2, 2]];
$extraStudents = 2;
echo maxAverageRatio($classes, $extraStudents); // Output: 0.78333
$classes = [[2, 4], [3, 9], [4, 5], [2, 10]];
$extraStudents = 4;
echo maxAverageRatio($classes, $extraStudents); // Output: 0.53485
?> Explanation:
Complexity:
This implementation efficiently distributes the extra students and computes the maximum average pass ratio. |
Beta Was this translation helpful? Give feedback.
We can use a max-heap (priority queue). This is because we need to efficiently find the class that benefits the most (maximizes the change in pass ratio) when adding an extra student.
Approach:
Understand the Gain Calculation:
gain = (pass + 1)/(total + 1) - pass/total
extraStudents
optimally.Use a Max-Heap:
[negative gain, pass, total]
. (We use a negative gain because PHP'sSplPriori…