Skip to content

Commit 76d112c

Browse files
authored
Create maximum-average-pass-ratio.cpp
1 parent 11d031c commit 76d112c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

C++/maximum-average-pass-ratio.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n + mlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
7+
static const auto& profit = [](double a, double b) {
8+
return (a + 1) / (b + 1) - a / b;
9+
};
10+
11+
vector<tuple<double, int, int>> max_heap;
12+
for (const auto& c : classes) {
13+
max_heap.emplace_back(profit(c[0], c[1]), c[0], c[1]);
14+
}
15+
make_heap(begin(max_heap), end(max_heap));
16+
for (; extraStudents > 0; --extraStudents) {
17+
auto [_, a, b] = max_heap.front();
18+
++a, ++b;
19+
pop_heap(begin(max_heap), end(max_heap)); max_heap.pop_back();
20+
max_heap.emplace_back(profit(a, b), a, b); push_heap(begin(max_heap), end(max_heap));
21+
}
22+
return accumulate(cbegin(max_heap), cend(max_heap), 0.0,
23+
[](const auto& total, const auto& x) {
24+
return total + float(get<1>(x)) / get<2>(x);
25+
}) / size(classes);
26+
}
27+
};

0 commit comments

Comments
 (0)