forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum-average-pass-ratio.cpp
27 lines (25 loc) · 1.02 KB
/
maximum-average-pass-ratio.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Time: O(n + mlogn)
// Space: O(n)
class Solution {
public:
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
static const auto& profit = [](double a, double b) {
return (a + 1) / (b + 1) - a / b;
};
vector<tuple<double, int, int>> max_heap;
for (const auto& c : classes) {
max_heap.emplace_back(profit(c[0], c[1]), c[0], c[1]);
}
make_heap(begin(max_heap), end(max_heap));
for (; extraStudents > 0; --extraStudents) {
auto [_, a, b] = max_heap.front();
++a, ++b;
pop_heap(begin(max_heap), end(max_heap)); max_heap.pop_back();
max_heap.emplace_back(profit(a, b), a, b); push_heap(begin(max_heap), end(max_heap));
}
return accumulate(cbegin(max_heap), cend(max_heap), 0.0,
[](const auto& total, const auto& x) {
return total + float(get<1>(x)) / get<2>(x);
}) / size(classes);
}
};