Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi 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 <= 105classes[i].length == 21 <= passi <= totali <= 1051 <= extraStudents <= 105Problem summary: 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] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[[1,2],[3,5],[2,2]] 2
[[2,4],[3,9],[4,5],[2,10]] 4
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1792: Maximum Average Pass Ratio
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;
}
}
// Accepted solution for LeetCode #1792: Maximum Average Pass Ratio
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 any) { *h = append(*h, v.(tuple)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
# Accepted solution for LeetCode #1792: Maximum Average Pass Ratio
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)
// Accepted solution for LeetCode #1792: Maximum Average Pass Ratio
use std::cmp::Ordering;
use std::collections::BinaryHeap;
impl Solution {
pub fn max_average_ratio(classes: Vec<Vec<i32>>, extra_students: i32) -> f64 {
struct Node {
gain: f64,
a: i32,
b: i32,
}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.gain == other.gain
}
}
impl Eq for Node {}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.gain.partial_cmp(&other.gain)
}
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
fn calc_gain(a: i32, b: i32) -> f64 {
(a + 1) as f64 / (b + 1) as f64 - a as f64 / b as f64
}
let n = classes.len() as f64;
let mut pq = BinaryHeap::new();
for c in classes {
let a = c[0];
let b = c[1];
pq.push(Node {
gain: calc_gain(a, b),
a,
b,
});
}
let mut extra = extra_students;
while extra > 0 {
if let Some(mut node) = pq.pop() {
node.a += 1;
node.b += 1;
node.gain = calc_gain(node.a, node.b);
pq.push(node);
}
extra -= 1;
}
let mut sum = 0.0;
while let Some(node) = pq.pop() {
sum += node.a as f64 / node.b as f64;
}
sum / n
}
}
// Accepted solution for LeetCode #1792: Maximum Average Pass Ratio
function maxAverageRatio(classes: number[][], extraStudents: number): number {
function calcGain(a: number, b: number): number {
return (a + 1) / (b + 1) - a / b;
}
const pq = new PriorityQueue<[number, number]>(
(p, q) => calcGain(q[0], q[1]) - calcGain(p[0], p[1]),
);
for (const [a, b] of classes) {
pq.enqueue([a, b]);
}
while (extraStudents-- > 0) {
const item = pq.dequeue();
const [a, b] = item;
pq.enqueue([a + 1, b + 1]);
}
let ans = 0;
while (!pq.isEmpty()) {
const item = pq.dequeue()!;
const [a, b] = item;
ans += a / b;
}
return ans / classes.length;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.