2141. Maximum Running Time of N Computers #2482
-
|
Topics: You have Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We can use binary search to find the maximum time We set the lower bound Approach:
Let's implement this solution in PHP: 2141. Maximum Running Time of N Computers <?php
/**
* @param Integer $n
* @param Integer[] $batteries
* @return Integer
*/
function maxRunTime($n, $batteries) {
$total = array_sum($batteries);
$low = 0;
$high = intdiv($total, $n);
while ($low < $high) {
$mid = intdiv($low + $high + 1, 2);
$required = $n * $mid;
$sum = 0;
foreach ($batteries as $b) {
$sum += min($b, $mid);
if ($sum >= $required) {
break;
}
}
if ($sum >= $required) {
$low = $mid;
} else {
$high = $mid - 1;
}
}
return $low;
}
// Test cases
echo maxRunTime(2, [3,3,3]) . "\n"; // Output: 4
echo maxRunTime(2, [1,1,1,1]) . "\n"; // Output: 2
?>Explanation:
Complexity Analysis
Solution Walkthrough
|
Beta Was this translation helpful? Give feedback.


We can use binary search to find the maximum time
Tsuch that allncomputers can run simultaneously forTminutes. For a givenT, we check if the sum ofmin(batteries[i], T)over all batteries is at leastn × T. This condition is necessary and sufficient because each battery can contribute at mostTminutes to the total runtime (or its full capacity if less thanT), and we can schedule the batteries arbitrarily.We set the lower bound
low = 0and the upper boundhigh = ⌊sum(batteries)⌋. Then we perform binary search to find the maximumTthat satisfies the condition.Approach: