progress

~/problems / Binary search / Binary search on the answer

Earliest time to build t products

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

Write min_time(machines: list[int], t: int) -> int.

A factory has several machines working in parallel. Machine i needs machines[i] seconds to build one product, and it keeps building products back to back. Return the smallest time T by which the machines together can have finished at least t products.

Example: machines = [2, 3, 7], t = 7 gives 8: by time 8 the machines have built 4 + 2 + 1 = 7 products (at time 7 it's only 3 + 2 + 1 = 6).

Constraints: 1 <= len(machines) <= 2 * 10^4, 1 <= machines[i], t <= 10^9. The answer can be as large as 10^18.

Simulating second by second (or product by product) can take up to 10^18 steps, and some correctness tests are that big, so search the answer. ⭐ Bonus: a speed test earns a star at O(n log(answer)). In C++/Java, stop summing once you reach t, or the count can overflow 64 bits.

Show hint

by time T the machines have built sum(T // m for m in machines) products, and that number only grows with T. The answer is at most min(machines) * t.

Topic: Binary search on the answer. Monotonic feasibility check + search the smallest value that works.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc