LeetCode 1792: Maximum Average Pass Ratio

Problem Description

Explanation:

To maximize the average pass ratio across all classes, we need to assign the extra students to classes in a way that increases the pass ratio the most. We can achieve this by calculating the increase in pass ratio for each class when an extra student is assigned and then greedily assigning the extra students to the class with the maximum increase until we run out of extra students.

Algorithm:

  1. Create a priority queue to store the classes based on the increase in pass ratio.
  2. Calculate the increase in pass ratio for each class if an extra student is assigned.
  3. Push the classes into the priority queue based on the maximum increase in pass ratio.
  4. Pop the class with the maximum increase, assign an extra student to it, and update its pass ratio.
  5. Repeat step 4 until all extra students are assigned.
  6. Calculate the average pass ratio after assigning the extra students.

Time Complexity: O(nlogn) where n is the number of classes. Space Complexity: O(n) for the priority queue.

:

Solutions

import java.util.PriorityQueue;

class Solution {
    public double maxAverageRatio(int[][] classes, int extraStudents) {
        PriorityQueue<double[]> pq = new PriorityQueue<>((a, b) -> Double.compare(b[0], a[0]));

        for (int[] cl : classes) {
            double pass = cl[0];
            double total = cl[1];
            double increase = (pass + 1) / (total + 1) - pass / total;
            pq.offer(new double[]{increase, pass, total});
        }

        while (extraStudents > 0) {
            double[] cl = pq.poll();
            cl[1]++;
            cl[2]++;
            double newIncrease = (cl[1] + 1) / (cl[2] + 1) - cl[1] / cl[2];
            pq.offer(new double[]{newIncrease, cl[1], cl[2]});
            extraStudents--;
        }

        double sum = 0;
        for (double[] cl : pq) {
            sum += cl[1] / cl[2];
        }

        return sum / classes.length;
    }
}

Loading editor...