| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MaximumAveragePassRatio; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumAveragePassRatioPriorityQueue : IMaximumAveragePassRatio |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="classes"></param> |
| | 22 | | /// <param name="extraStudents"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public double MaxAverageRatio(int[][] classes, int extraStudents) |
| 2 | 25 | | { |
| 2 | 26 | | var ratiosPriorityQueue = new PriorityQueue<(int Pass, int Total), double>(); |
| | 27 | |
|
| 20 | 28 | | foreach (var @class in classes) |
| 7 | 29 | | { |
| 7 | 30 | | var pass = @class[0]; |
| 7 | 31 | | var total = @class[1]; |
| | 32 | |
|
| 7 | 33 | | var delta = GetDelta(pass, total); |
| | 34 | |
|
| 7 | 35 | | ratiosPriorityQueue.Enqueue((pass, total), -delta); |
| 7 | 36 | | } |
| | 37 | |
|
| 16 | 38 | | for (var i = 0; i < extraStudents; i++) |
| 6 | 39 | | { |
| 6 | 40 | | var ratio = ratiosPriorityQueue.Dequeue(); |
| | 41 | |
|
| 6 | 42 | | ratio.Pass++; |
| 6 | 43 | | ratio.Total++; |
| | 44 | |
|
| 6 | 45 | | var delta = GetDelta(ratio.Pass, ratio.Total); |
| | 46 | |
|
| 6 | 47 | | ratiosPriorityQueue.Enqueue((ratio.Pass, ratio.Total), -delta); |
| 6 | 48 | | } |
| | 49 | |
|
| 2 | 50 | | double average = 0; |
| | 51 | |
|
| 9 | 52 | | while (ratiosPriorityQueue.Count > 0) |
| 7 | 53 | | { |
| 7 | 54 | | var ratio = ratiosPriorityQueue.Dequeue(); |
| | 55 | |
|
| 7 | 56 | | average += (double)ratio.Pass / ratio.Total / classes.Length; |
| 7 | 57 | | } |
| | 58 | |
|
| 2 | 59 | | return average; |
| 2 | 60 | | } |
| | 61 | |
|
| | 62 | | private static double GetDelta(int pass, int total) |
| 13 | 63 | | { |
| 13 | 64 | | var currentRatio = (double)pass / total; |
| 13 | 65 | | var newRatio = (double)(pass + 1) / (total + 1); |
| | 66 | |
|
| 13 | 67 | | return newRatio - currentRatio; |
| 13 | 68 | | } |
| | 69 | | } |