[LeetCode] Maximum Average Pass Ratio

1792. Maximum Average Pass Ratio

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
auto Compare = [](pair<long long, long long> &a, pair<long long, long long> &b) {
auto [at, ap] = a;
auto [bt, bp] = b;
auto A = 1.0 * (at - ap) / (at * (at + 1));
auto B = 1.0 * (bt - bp) / (bt * (bt + 1));
return A < B;
};
priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, decltype(Compare)> pq(Compare);
double res = 0;
for(auto& c : classes) {
int p = c[0], t = c[1];
if(p == t) res += 1;
else pq.push({t, p});
}
while(extraStudents-- and !pq.empty()) {
auto [t, p] = pq.top(); pq.pop();
pq.push({t + 1, p + 1});
}
while(!pq.empty()) {
auto [t, p] = pq.top(); pq.pop();
res += 1.0 * p / t;
}
return res / classes.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/09/PS/LeetCode/maximum-average-pass-ratio/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.