1792. Maximum Average Pass Ratio
Difficulty: Medium
Topics: Array, Greedy, Heap (Priority Queue)
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:
Example 2:
Constraints:
Hint:
Solution:
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.
Understand the Gain Calculation:
Use a Max-Heap:
Iteratively Distribute Extra Students:
Calculate the Final Average:
Let's implement this solution in PHP: 1792. Maximum Average Pass Ratio
Explanation:
Heap Setup:
- We use a max-heap (priority queue) to prioritize classes based on their potential improvement in pass ratio when an extra student is added.
- In PHP, SplPriorityQueue is used for the heap. The higher the priority value, the earlier the class is processed.
Distributing Extra Students:
- For each extra student, we extract the class with the highest potential improvement from the heap.
- After adding one student to that class, we recalculate its potential improvement and reinsert it into the heap.
Final Average Calculation:
- After distributing all extra students, we calculate the total pass ratio for all classes and return the average.
Precision:
- The calculations are performed using floating-point arithmetic, which ensures answers are accurate to 10^-5 as required.
Complexity:
Time Complexity:
Space Complexity:
This implementation efficiently distributes the extra students and computes the maximum average pass ratio.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Maximum Average Pass Ratio. For more information, please follow other related articles on the PHP Chinese website!