Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1792.html

1792. Maximum Average Pass Ratio

Level

Medium

Description

There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [pass_i, total_i]. You know beforehand that in the i-th class, there are total_i total students, but only pass_i number of students will pass the exam.

You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.

The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.

Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2

Output: 0.78333

Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.

Example 2:

Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4

Output: 0.53485

Constraints:

  • 1 <= classes.length <= 10^5
  • classes[i].length == 2
  • 1 <= pass_i <= total_i <= 10^5
  • 1 <= extraStudents <= 10^5

Solution

Use a greedy approach. For each extra student, add the extra student to the class so that the class’ pass ratio increases the most. Use a priority queue to implement the greedy approach. After all extra students are added to the classes, calculate the average ratio and return.

  • class Solution {
        public double maxAverageRatio(int[][] classes, int extraStudents) {
            PriorityQueue<int[]> priorityQueue = new PriorityQueue<int[]>(new Comparator<int[]>() {
                public int compare(int[] arr1, int[] arr2) {
                    long increase1Numerator = (long) arr1[1] - (long) arr1[0];
                    long increase1Denominator = (long) arr1[1] * (long) (arr1[1] + 1);
                    long increase2Numerator = (long) arr2[1] - (long) arr2[0];
                    long increase2Denominator = (long) arr2[1] * (long) (arr2[1] + 1);
                    long difference = increase2Numerator * increase1Denominator - increase1Numerator * increase2Denominator;
                    if (difference > 0)
                        return 1;
                    else if (difference < 0)
                        return -1;
                    else
                        return 0;
                }
            });
            for (int[] arr : classes)
                priorityQueue.offer(new int[]{arr[0], arr[1]});
            for (int i = 0; i < extraStudents; i++) {
                int[] arr = priorityQueue.poll();
                int[] newArr = {arr[0] + 1, arr[1] + 1};
                priorityQueue.offer(newArr);
            }
            double averageRatio = 0;
            while (!priorityQueue.isEmpty()) {
                int[] arr = priorityQueue.poll();
                averageRatio += 1.0 * arr[0] / arr[1];
            }
            averageRatio /= classes.length;
            return averageRatio;
        }
    }
    
    ############
    
    class Solution {
        public double maxAverageRatio(int[][] classes, int extraStudents) {
            PriorityQueue<double[]> pq = new PriorityQueue<>((a, b) -> {
                double x = (a[0] + 1) / (a[1] + 1) - a[0] / a[1];
                double y = (b[0] + 1) / (b[1] + 1) - b[0] / b[1];
                return Double.compare(y, x);
            });
            for (var e : classes) {
                pq.offer(new double[] {e[0], e[1]});
            }
            while (extraStudents-- > 0) {
                var e = pq.poll();
                double a = e[0] + 1, b = e[1] + 1;
                pq.offer(new double[] {a, b});
            }
            double ans = 0;
            while (!pq.isEmpty()) {
                var e = pq.poll();
                ans += e[0] / e[1];
            }
            return ans / classes.length;
        }
    }
    
  • // OJ: https://leetcode.com/problems/maximum-average-pass-ratio/
    // Time: O((E + C)logC)
    // Space: O(C)
    class Solution {
        double dist(pair<int, int> &p) {
            return (double)(p.first + 1) / (p.second + 1) - (double)p.first / p.second;
        }
    public:
        double maxAverageRatio(vector<vector<int>>& C, int E) {
            int ones = 0;
            auto cmp = [&](auto &a, auto &b) { return dist(a) < dist(b); };
            priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
            for (auto &c : C) {
                if (c[0] == c[1]) ++ones;
                else pq.emplace(c[0], c[1]);
            }
            for (int i = 0; i < E && pq.size(); ++i) {
                auto [a, b] = pq.top();
                pq.pop();
                pq.emplace(a + 1, b + 1);
            }
            double total = 0;
            while (pq.size()) {
                auto [a, b] = pq.top();
                pq.pop();
                total += (double)a / b;
            }
            return (total + ones) / C.size();
        }
    };
    
  • class Solution:
        def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
            h = [(a / b - (a + 1) / (b + 1), a, b) for a, b in classes]
            heapify(h)
            for _ in range(extraStudents):
                _, a, b = heappop(h)
                a, b = a + 1, b + 1
                heappush(h, (a / b - (a + 1) / (b + 1), a, b))
            return sum(v[1] / v[2] for v in h) / len(classes)
    
    ############
    
    # 1792. Maximum Average Pass Ratio
    # https://leetcode.com/problems/maximum-average-pass-ratio/
    
    class Solution:
        def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
            def profit(a, b):
                return (a + 1) / (b + 1) - a / b
            
            heap = []
            for a,b in classes:
                heap.append((-profit(a, b), a, b))
            
            heapq.heapify(heap)
            
            for _ in range(extraStudents):
                _, a, b = heapq.heappop(heap)
                heapq.heappush(heap, (-profit(a + 1, b + 1), a + 1, b + 1))
            
            return sum(a / b for _, a, b in heap) / len(classes)
    
    
  • func maxAverageRatio(classes [][]int, extraStudents int) float64 {
    	pq := hp{}
    	for _, e := range classes {
    		a, b := e[0], e[1]
    		x := float64(a+1)/float64(b+1) - float64(a)/float64(b)
    		heap.Push(&pq, tuple{x, a, b})
    	}
    	for i := 0; i < extraStudents; i++ {
    		e := heap.Pop(&pq).(tuple)
    		a, b := e.a+1, e.b+1
    		x := float64(a+1)/float64(b+1) - float64(a)/float64(b)
    		heap.Push(&pq, tuple{x, a, b})
    	}
    	var ans float64
    	for len(pq) > 0 {
    		e := heap.Pop(&pq).(tuple)
    		ans += float64(e.a) / float64(e.b)
    	}
    	return ans / float64(len(classes))
    }
    
    type tuple struct {
    	x float64
    	a int
    	b int
    }
    
    type hp []tuple
    
    func (h hp) Len() int { return len(h) }
    func (h hp) Less(i, j int) bool {
    	a, b := h[i], h[j]
    	return a.x > b.x
    }
    func (h hp) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
    func (h *hp) Push(v interface{}) { *h = append(*h, v.(tuple)) }
    func (h *hp) Pop() interface{}   { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
    

All Problems

All Solutions