From 1c25b8a606482679bbeb5c2360bfede41d88d2e8 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 15 Dec 2024 23:02:40 +0100 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB1792.=20Maximum=20Average=20P?= =?UTF-8?q?ass=20Ratio=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/maximum-average-pass-ratio/ Signed-off-by: Matej Focko --- cs/maximum-average-pass-ratio.cs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 cs/maximum-average-pass-ratio.cs 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; + } +}