#1792

Maximum Average Pass Ratio

Medium
ArrayGreedyHeap (Priority Queue)Greedy AlgorithmsPriority Queue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + extraStudents log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n + extraStudents log n)Space O(n)

The optimal solution uses a greedy approach with a priority queue to always assign extra students to the class where they will have the most significant impact on the average pass ratio. This is efficient and ensures we maximize the average pass ratio.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a max-heap (priority queue) to store the classes based on the potential increase in pass ratio when an extra student is added.
  2. 2Step 2: For each class, calculate the initial pass ratio and the potential increase if one extra student is added.
  3. 3Step 3: Assign extra students to the class with the highest potential increase until all extra students are assigned.
  4. 4Step 4: Calculate the final average pass ratio.
solution.py14 lines
1# Full working Python code
2import heapq
3
4def maxAverageRatio(classes, extraStudents):
5    heap = []
6    for pass_i, total_i in classes:
7        heapq.heappush(heap, (-((pass_i + 1) / (total_i + 1) - pass_i / total_i), pass_i, total_i))
8    for _ in range(extraStudents):
9        change, pass_i, total_i = heapq.heappop(heap)
10        pass_i += 1
11        total_i += 1
12        heapq.heappush(heap, (-((pass_i + 1) / (total_i + 1) - pass_i / total_i), pass_i, total_i))
13    total_ratio = sum(pass_i / total_i for _, pass_i, total_i in heap)
14    return total_ratio / len(classes)

Complexity note: The complexity is dominated by the heap operations, where we perform log n operations for each of the extra students, leading to O(n log n) for the initial heap creation and O(extraStudents log n) for the student assignments.

  • 1The impact of adding an extra student diminishes as more students are added to a class.
  • 2Using a priority queue allows us to efficiently determine which class to assign the next extra student to maximize the increase in average pass ratio.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.