LeetCode/cs/maximum-average-pass-ratio.cs

32 lines
1.1 KiB
C#
Raw Normal View History

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;
}
}