diff --git a/cs/maximum-average-pass-ratio.cs b/cs/maximum-average-pass-ratio.cs new file mode 100644 index 0000000..b08ec40 --- /dev/null +++ b/cs/maximum-average-pass-ratio.cs @@ -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(); + 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; + } +}