Skip to content

Commit 6fff064

Browse files
authored
Update maximum-running-time-of-n-computers.cpp
1 parent ef64e41 commit 6fff064

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

C++/maximum-running-time-of-n-computers.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,29 @@ class Solution {
1515
return total / n;
1616
}
1717
};
18+
19+
// Time: O(nlogr), r is the range of possible minutes
20+
// Space: O(1)
21+
// binary search
22+
class Solution2 {
23+
public:
24+
long long maxRunTime(int n, vector<int>& batteries) {
25+
auto check = [&n, &batteries](int64_t x) {
26+
return accumulate(cbegin(batteries), cend(batteries), 0ll,
27+
[&x](const auto& total, const int64_t b) {
28+
return total + min(b, x);
29+
}) >= n * x;
30+
};
31+
int64_t left = *min_element(cbegin(batteries), cend(batteries));
32+
int64_t right = accumulate(cbegin(batteries), cend(batteries), 0ll) / n;
33+
while (left <= right) {
34+
const auto mid = left + (right - left) / 2;
35+
if (!check(mid)) {
36+
right = mid - 1;
37+
} else {
38+
left = mid + 1;
39+
}
40+
}
41+
return right;
42+
}
43+
};

0 commit comments

Comments
 (0)