1917. Maximum Average Pass Ratio¶
Difficulty: Medium
LeetCode Problem View on GitHub
1917. Maximum Average Pass Ratio
Medium
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:
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 <= 105classes[i].length == 21 <= passi <= totali <= 1051 <= extraStudents <= 105
Solution¶
class Solution {
static class Tuple {
double delta, pass, total;
public Tuple(double delta, double pass, double total) {
this.delta = delta;
this.pass = pass;
this.total = total;
}
@Override
public String toString() {
return "(" + delta + " " + pass + " " + total + ")";
}
}
static class sorting implements Comparator<Tuple> {
@Override
public int compare(Tuple first, Tuple second) {
return Double.compare(second.delta , first.delta);
}
}
public double maxAverageRatio(int[][] classes, int extraStudents) {
PriorityQueue<Tuple> pq = new PriorityQueue<>(new sorting());
for(int current[] : classes) {
double pass = (double)current[0];
double total = (double)current[1];
double delta = (double)(pass + 1) / (double)(total + 1) - (double)(pass) / (double)(total);
pq.offer(new Tuple(delta, pass, total));
}
while(extraStudents > 0) {
double pass = pq.peek().pass, total = pq.peek().total, delta = pq.peek().delta;
pass++;
total++;
double newDelta = (double)(pass + 1) / (double)(total + 1) - (double)(pass) / (double)(total);
pq.poll();
pq.offer(new Tuple(newDelta, pass, total));
extraStudents--;
}
double ans = 0;
int total = pq.size();
while(!pq.isEmpty()) {
ans += (double)pq.peek().pass / (double)pq.peek().total;
pq.poll();
}
return (double)(ans / (double) total);
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here