- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 37 lines of C++ from the credited upstream file 1792.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {4 5 priority_queue<tuple<double, int, int>> maxHeap;6 7 for (const vector<int>& c : classes) {8 const int pass = c[0];9 const int total = c[1];10 maxHeap.emplace(extraPassRatio(pass, total), pass, total);11 }12 13 for (int i = 0; i < extraStudents; ++i) {14 const auto [_, pass, total] = maxHeap.top();15 maxHeap.pop();16 maxHeap.emplace(extraPassRatio(pass + 1, total + 1), pass + 1, total + 1);17 }18 19 double ratioSum = 0;20 21 while (!maxHeap.empty()) {22 const auto [_, pass, total] = maxHeap.top();23 maxHeap.pop();24 ratioSum += pass / static_cast<double>(total);25 }26 27 return ratioSum / classes.size();28 }29 30 private:31 32 double extraPassRatio(int pass, int total) {33 return (pass + 1) / static_cast<double>(total + 1) -34 pass / static_cast<double>(total);35 }36};37