the third one in Weekly Contest 232.
Difficulty : Medium
Related Topics : Heap
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
, whereclasses[i] = [passi, totali]
. You know beforehand that in thei
^th
class, there aretotal
i
total students, but onlypass
i
number of students will pass the exam.You are also given an integer
extraStudents
. There are anotherextraStudents
brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of theextraStudents
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.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.
Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485
1 <= classes.length <= 10^5
classes[i].length == 2
1 <= pass
i
<= total
i
<= 10^5
1 <= extraStudents <= 10^5
- mine
- Java
Runtime: 460 ms, faster than 100.00%, Memory Usage: 95.3 MB, less than 100.00% of Java online submissions
// O(N * logN)time // O(N)space public double maxAverageRatio(int[][] classes, int extraStudents) { PriorityQueue<double[]> doubles = new PriorityQueue<>((o1, o2) -> { double t1 = (o1[0] + 1) / (o1[1] + 1) - o1[0] / o1[1]; double t2 = (o2[0] + 1) / (o2[1] + 1) - o2[0] / o2[1]; if (t1 == t2) return 0; return t1 - t2 > 0 ? -1 : 1; }); for (int[] c : classes) { double[] t = new double[3]; t[0] = c[0]; t[1] = c[1]; t[2] = c[0] * 1.0D / c[1]; doubles.add(t); } while (extraStudents > 0) { extraStudents--; double[] t = doubles.poll(); t[0] += 1; t[1] += 1; t[2] = t[0] * 1.0D / t[1]; doubles.add(t); } double t = 0; while (!doubles.isEmpty()) t += doubles.poll()[2]; return t / classes.length; }
- Java