forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-running-time-of-n-computers.cpp
43 lines (41 loc) · 1.35 KB
/
maximum-running-time-of-n-computers.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Time: O(nlogm)
// Space: O(1)
// greedy
class Solution {
public:
long long maxRunTime(int n, vector<int>& batteries) {
int64_t total = accumulate(cbegin(batteries), cend(batteries), 0ll);
make_heap(begin(batteries), end(batteries));
while (batteries.front() > total / n) {
--n;
total -= batteries.front();
pop_heap(begin(batteries), end(batteries)); batteries.pop_back();
}
return total / n;
}
};
// Time: O(nlogr), r is the range of possible minutes
// Space: O(1)
// binary search
class Solution2 {
public:
long long maxRunTime(int n, vector<int>& batteries) {
auto check = [&n, &batteries](int64_t x) {
return accumulate(cbegin(batteries), cend(batteries), 0ll,
[&x](const auto& total, const int64_t b) {
return total + min(b, x);
}) >= n * x;
};
int64_t left = *min_element(cbegin(batteries), cend(batteries));
int64_t right = accumulate(cbegin(batteries), cend(batteries), 0ll) / n;
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (!check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
};