Sponsored
Sponsored
We can use binary search to determine the maximum possible time all computers can run simultaneously. The key observation is that if it's possible to run the computers for t minutes, it's also possible to run them for any time less than t. Similarly, if you cannot run them for t minutes, you cannot for any time greater than t. Here's how we can implement this:
Time Complexity: O(m log(max_time)), where m is the number of batteries.
Space Complexity: O(1), as no extra space proportional to input size is used.
1#include <vector>
2#include <algorithm>
3
4bool canRunSimultaneously(long long t, const std::vector<int>& batteries, int n) {
5 long long timeSum = 0;
6 for (long long battery : batteries) {
7 timeSum += (battery < t ? battery : t);
8 }
9 return timeSum >= t * n;
10}
11
12long long maxRunTime(int n, std::vector<int>& batteries) {
13 long long totalSum = 0;
14 for (int battery : batteries) {
totalSum += battery;
}
long long left = 0, right = totalSum / n;
while (left < right) {
long long mid = right - (right - left) / 2;
if (canRunSimultaneously(mid, batteries, n)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
This C++ solution similarly implements the binary search approach. It uses a helper function canRunSimultaneously
to determine feasibility. By checking if the total possible time is enough to sustain t * n
time, the search space is narrowed until the maximum feasible t
is found, using the advantage of the vector data structure.
A straightforward approach is sorting the batteries by their available time and then using a greedy method to allocate the longest available running time to any computer that can accommodate it. The goal is to utilize batteries to maximize the running time in descending order until we've depleted either the batteries or optimized distributions.
Time Complexity: O(m log m), because of the sorting step.
Space Complexity: O(1), in-place operations on the battery array.
This JavaScript function sorts the battery life array in a descending order, then attempts to evenly distribute the overall battery life. It skips over excess values where the potential maximal round-up operation exceeds current calculated values of battery life.