Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Longest time n machines can run on shared batteries

Hard · Target 30 minutes · Binary search · Type asked atGoogleCitadel

You have n machines and a list of batteries; battery i holds batteries[i] minutes of charge. Each machine needs exactly one battery at a time. At any whole minute you may swap batteries between machines instantly, and a battery's remaining charge stays with it. Return the largest number of minutes for which all n machines can run at the same time.

Examples

InputOutputWhy
n = 2, batteries = [3, 3, 3]49 minutes of charge for two machines: 4 minutes each, with swaps.
n = 2, batteries = [1, 1, 1, 1]2
n = 2, batteries = [100, 1]1The big battery cannot power two machines at once.

Constraints

  • 1 ≤ n ≤ batteries.length ≤ 10⁵
  • 1 ≤ batteries[i] ≤ 10⁹

Hints

Hint 1

Fix a target t. How much of battery i can actually be used in t minutes?

Hint 2

At most min(batteries[i], t): one battery can power only one machine at a time.

Hint 3

The machines need n·t minutes of charge, so t is achievable when Σ min(b, t) ≥ n·t, and it then turns out to be enough as well. Search the last t that passes, up to sum / n.

Where people lose marks

  • Testing Σ b ≥ n · t without the cap: [100, 1] with n = 2 would claim 50 minutes.
  • Overflowing n · t or the sum in 32 bits.
  • Rounding the midpoint down while setting lo = mid.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.