- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 34 lines of Java from the credited upstream file 1792.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public double maxAverageRatio(int[][] classes, int extraStudents) {3 4 PriorityQueue<T> maxHeap =5 new PriorityQueue<>((a, b) -> Double.compare(b.extraPassRatio, a.extraPassRatio));6 7 for (int[] c : classes) {8 final int pass = c[0];9 final int total = c[1];10 maxHeap.offer(new T(getExtraPassRatio(pass, total), pass, total));11 }12 13 for (int i = 0; i < extraStudents; ++i) {14 final int pass = maxHeap.peek().pass;15 final int total = maxHeap.poll().total;16 maxHeap.offer(new T(getExtraPassRatio(pass + 1, total + 1), pass + 1, total + 1));17 }18 19 double ratioSum = 0;20 21 while (!maxHeap.isEmpty())22 ratioSum += maxHeap.peek().pass / (double) maxHeap.poll().total;23 24 return ratioSum / classes.length;25 }26 27 28 private double getExtraPassRatio(int pass, int total) {29 return (pass + 1) / (double) (total + 1) - pass / (double) total;30 }31 32 private record T(double extraPassRatio, int pass, int total){};33}34