#2141
Maximum Running Time of N Computers
expert · 1260 · lc hard +32 · verified · 56.4% accepted · 2,439 likes · top 51%
Description
You have n computers and an array batteries where batteries[i] is the runtime in minutes provided by the ith battery. You want all n computers running simultaneously.
At any integer point in time, you can swap batteries between computers at no cost. Each battery can only be used, never recharged.
Return the maximum number of minutes all n computers can run simultaneously.
Example 1:
Input: n = 2, batteries = [3,3,3]
Output: 4
Explanation:
Initially, insert battery 0 into the first computer and battery 1 into the second computer.
After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.
At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.
By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.
We can run the two computers simultaneously for at most 4 minutes, so we return 4.
Example 2:
Input: n = 2, batteries = [1,1,1,1]
Output: 2
Explanation:
Initially, insert battery 0 into the first computer and battery 2 into the second computer.
After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer.
After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.
We can run the two computers simultaneously for at most 2 minutes, so we return 2.
Code
1
2
3