DSA Heaps

Maximum Average Pass Ratio

Distribute extra students to maximize average class pass ratio — max-heap keyed by marginal improvement.

Medium
Time O((n + k) log n) Space O(n)
LeetCode
6 min read
heaps greedy

Problem#

Each class has pass / total ratio. You may add extraStudents who pass each class they’re assigned to (assigned to exactly one). Return the maximum possible average pass ratio across classes.

Examples#

  • classes = [[1,2],[3,5],[2,2]], extra = 20.78333

Constraints#

  • 1 <= classes.length <= 10^5.

Approach#

Marginal gain of adding one student to (p, t) is (p+1)/(t+1) - p/t. The gain decreases as more are added (concavity), so greedy max-heap by marginal gain is optimal.

Solution#

Maximum Average Pass Ratio
class Solution {
public:
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
auto gain = [](double p, double t){
return (p + 1) / (t + 1) - p / t;
};
priority_queue<tuple<double,int,int>> pq;
for (auto& c : classes) {
pq.emplace(gain(c[0], c[1]), c[0], c[1]);
}
while (extraStudents--) {
auto [g, p, t] = pq.top(); pq.pop();
++p; ++t;
pq.emplace(gain(p, t), p, t);
}
double total = 0;
while (!pq.empty()) {
auto [g, p, t] = pq.top(); pq.pop();
total += (double)p / t;
}
return total / classes.size();
}
};

Editorial#

Concavity (each successive student helps less than the previous) is what makes the greedy optimal. The closed-form delta (p+1)/(t+1) - p/t saves us from comparing absolute ratios. Heap operations dominate at O(log n) each.

Complexity#

  • Time: O((n + k) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.