Problem 394822 · hard · Level 03 Linear Management & Searching

Longest Run on a Bank of Batteries

binary search on the answer · greedy · math

You need to keep n machines running simultaneously. Each machine holds exactly one battery at a time, and batteries[i] is how many minutes battery i lasts. Batteries may be moved between machines at any moment, as often as you like, with no loss. Return the maximum number of whole minutes during which all n machines can run at the same time.

Examples

Input:  n = 3, batteries = [4, 4, 4, 4]
Output: 5
Explanation: call the batteries A, B, C and D. 5 minutes need 15 battery-minutes and 16 exist. In
minutes 1 to 4 a different battery rests each minute, so each has run 3 minutes; minute 5 uses A, B and C.

Input:  n = 2, batteries = [6, 1, 1]
Output: 2
Explanation: the 6-minute battery can only power one machine at a time; the other machine has 2 minutes.

Input:  n = 3, batteries = [10, 10, 3, 5]
Output: 8

Constraints

  • 1 <= n <= len(batteries) <= 10**5, 1 <= batteries[i] <= 10**9
  • Required time: O(m log(sum(batteries) / n)). The answer can exceed every single battery.

Goals

  • Recognise that battery swapping lets you cap each battery's contribution
  • Search a value range far larger than any single input
Starting Python…