Maximum Average Pass Ratio (LeetCode 1792): Solution and Explanation

Medium
Array
Greedy
Heap (priority queue)

Each class has a pass ratio p / t. You may add extra students who always pass, one class at a time. Place all of them to make the average ratio across classes as large as possible.

Intuition

The number of classes never changes, so maximizing the average is the same as maximizing the sum of ratios. Each extra student adds something to exactly one ratio, so the question is where each student adds the most.

Adding one passing student to a class with ratio p / t changes it to (p + 1) / (t + 1). The increase, (p + 1) / (t + 1) - p / t = (t - p) / (t (t + 1)), is large for small classes with many failing students and tiny for big classes or classes that already pass everyone.

That gain only shrinks as a class receives more students. Because the returns diminish, a greedy rule is optimal: always give the next student to the class whose gain is largest right now. No later choice can make an earlier, bigger gain look worse.

Finding the largest gain quickly is a job for a max-heap. Pop the best class, give it a student, compute its new, smaller gain and push it back.

Approach: Max-heap on marginal gain

  1. For every class compute gain = (p + 1) / (t + 1) - p / t and push (gain, index) into a max-heap.
  2. Repeat extraStudents times: pop the class with the largest gain, increment its p and t, and push it back with its new gain.
  3. Sum p / t over all classes and divide by n.

Step-by-step example

classes = [[1,2],[3,5],[2,2]], extraStudents = 2
  1. Gains: class 0 is 2/3 - 1/2 = 0.1667, class 1 is 4/6 - 3/5 = 0.0667, class 2 is 0.
  2. Student 1 goes to class 0, which becomes 2/3. Its new gain is 3/4 - 2/3 = 0.0833.
  3. Class 0 still has the largest gain, so student 2 also goes there. It becomes 3/4.
  4. Ratios: 0.75 + 0.6 + 1.0 = 2.35. Average: 2.35 / 3 = 0.78333.

Code: Python, Java, C++

1class Solution:
2    def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
3        n = len(classes)
4        p = [c[0] for c in classes]
5        t = [c[1] for c in classes]
6        gain = lambda i: (p[i] + 1) / (t[i] + 1) - p[i] / t[i]
7        heap = [(-gain(i), i) for i in range(n)]
8        heapq.heapify(heap)
9        for _ in range(extraStudents):
10            _, i = heapq.heappop(heap)
11            p[i] += 1
12            t[i] += 1
13            heapq.heappush(heap, (-gain(i), i))
14        total = 0.0
15        for i in range(n):
16            total += p[i] / t[i]
17        return math.floor(total / n * 100000 + 0.5) / 100000
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O((n + k) log n)

Building the heap costs O(n log n) (or O(n) with heapify), and each of the k extra students does one pop and one push.

Space

O(n)

The heap holds one entry per class.

Other approaches

Linear scan per student (time O(n k), space O(1))

For each extra student, scan all classes for the largest gain. Simple but O(n k), which is far too slow when both are 10^5.

Common mistakes

  • Sorting by the current ratio instead of the gain. The class with the lowest ratio is not always the one that improves the most; size matters too.
  • Computing gains with integer division in Java, C++, C# or Go. Cast to double before dividing.
  • Forgetting to push the class back after adding a student. It may still be the best place for the next one.
  • Recomputing the whole average after each student. Only the final average is needed.

Frequently asked questions

Why is the greedy choice optimal?

Each class's gain sequence is decreasing as it receives more students. With diminishing returns, taking the largest available gain each time gives the largest possible total, by a standard exchange argument.

Why not give all students to the worst class?

Its gain drops after every student. Once another class offers a bigger gain, sending the next student there adds more to the sum.

Does precision matter?

Here the average is rounded to 5 decimal places, so every language prints the same value. Double precision is far more accurate than that. Ties between equal gains do not change the final average.

What is the complexity?

O((n + k) log n) time and O(n) space, where k is the number of extra students.