|
| 1 | +class Solution { |
| 2 | + public double maxAverageRatio(int[][] classes, int extraStudents) { |
| 3 | + PriorityQueue<SchoolClass> pq = new PriorityQueue<>(Collections.reverseOrder()); |
| 4 | + for (int[] schoolClass : classes) { |
| 5 | + pq.add(new SchoolClass(schoolClass[0], schoolClass[1])); |
| 6 | + } |
| 7 | + while (extraStudents-- > 0) { |
| 8 | + SchoolClass schoolClass = pq.poll(); |
| 9 | + schoolClass.increment(); |
| 10 | + pq.add(schoolClass); |
| 11 | + } |
| 12 | + double totalPassingRatio = 0.0; |
| 13 | + while (!pq.isEmpty()) { |
| 14 | + totalPassingRatio += pq.poll().passRatio(); |
| 15 | + } |
| 16 | + return totalPassingRatio / classes.length; |
| 17 | + } |
| 18 | + |
| 19 | + static class SchoolClass implements Comparable<SchoolClass> { |
| 20 | + |
| 21 | + private int passingStudents; |
| 22 | + private int totalStudents; |
| 23 | + |
| 24 | + public SchoolClass(int passingStudents, int totalStudents) { |
| 25 | + this.passingStudents = passingStudents; |
| 26 | + this.totalStudents = totalStudents; |
| 27 | + } |
| 28 | + |
| 29 | + void increment() { |
| 30 | + passingStudents++; |
| 31 | + totalStudents++; |
| 32 | + } |
| 33 | + |
| 34 | + double passRatio() { |
| 35 | + return ((double) passingStudents) / totalStudents; |
| 36 | + } |
| 37 | + |
| 38 | + double gain() { |
| 39 | + return ((double) (passingStudents + 1) / (totalStudents + 1)) - passRatio(); |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public int compareTo(SchoolClass o) { |
| 44 | + return Double.compare(gain(), o.gain()); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments