cs: add «1792. Maximum Average Pass Ratio»

URL:	https://leetcode.com/problems/maximum-average-pass-ratio/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-15 23:02:40 +01:00
parent 9989455c12
commit 1c25b8a606
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,31 @@
public class Solution {
private record struct ClassRecord(int Passes, int Students) {
public double PassRatio => (double)Passes / Students;
public double Gain => (double)(Passes + 1) / (Students + 1) - PassRatio;
}
public double MaxAverageRatio(int[][] classes, int extraStudents) {
// Construct the max heap based on the effect of adding student
var q = new PriorityQueue<ClassRecord, double>();
foreach (var classRecord in classes) {
var c = new ClassRecord(classRecord[0], classRecord[1]);
q.Enqueue(c, -c.Gain);
}
// Add the students based on priority
while (extraStudents-- > 0) {
var c = q.Dequeue();
var cWithNewStudent = new ClassRecord(c.Passes + 1, c.Students + 1);
q.Enqueue(cWithNewStudent, -cWithNewStudent.Gain);
}
// Calculate final pass ratio
double ratio = 0;
while (q.TryDequeue(out var c, out var gain)) {
ratio += c.PassRatio;
}
return ratio / classes.Length;
}
}