Skip to content

Instantly share code, notes, and snippets.

@igavrysh
Created December 16, 2024 00:05
Show Gist options
  • Save igavrysh/1ea5ca3e9b195cbcdaac467b45514b18 to your computer and use it in GitHub Desktop.
Save igavrysh/1ea5ca3e9b195cbcdaac467b45514b18 to your computer and use it in GitHub Desktop.
1792. Maximum Average Pass Ratio
/**
1792. Maximum Average Pass Ratio
https://leetcode.com/problems/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 <= 10^5
classes[i].length == 2
1 <= passi <= totali <= 10^5
1 <= extraStudents <= 10^T5
*/
class Solution {
public double maxAverageRatio(int[][] classes, int extraStudents) {
PriorityQueue<int[]> pq = new PriorityQueue<>((int[] p1, int[] p2) -> {
return -1*Double.compare(
(p1[0]+1.0)/(p1[1]+1.0) - p1[0]*1.0/p1[1],
(p2[0]+1.0)/(p2[1]+1.0) - p2[0]*1.0/p2[1]
);
});
double total_score = 0;
for (int i = 0; i < classes.length; i++) {
total_score += classes[i][0]*1.0/classes[i][1];
pq.offer(classes[i]);
}
while (extraStudents>0) {
int[] p = pq.poll();
total_score -= p[0]*1.0/p[1];
p[0]++;
p[1]++;
total_score += p[0]*1.0/p[1];
pq.offer(p);
extraStudents--;
}
return total_score / classes.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment