Skip to content
Preptima
mediumCodingMidSenior

Shipping packages within D days minimises a maximum. Now place m sensors at fixed positions so the closest pair is as far apart as possible. What changes in the binary search?

It is still binary search on the answer, over the gap rather than the positions, but the predicate flips. A gap that works means every smaller gap works, so you want the last feasible value, which needs lo = mid with a ceiling midpoint. Sort first, check each gap greedily, and the cost is O(n log n + n log R).

5 min readUpdated 2026-10-10

Answer

Short answer

The search space is the same kind of thing. You still run binary search on the answer, this time over candidate gaps, and test each gap with a linear greedy pass over the sorted positions. What flips is the predicate: if a gap of d is achievable, every smaller gap is too, so the feasible values come first and you want the last one. To maximise the minimum you keep mid on the low side, which forces a ceiling midpoint.

ship packages  capacity c   F F F F T T T   want first T   hi = mid, floor mid
place sensors  gap d        T T T F F F F   want last T    lo = mid, ceiling mid

Was this answer helpful?

Likely follow-ups

  • Rewrite the loop so it searches for the first infeasible gap instead. Which line changes, and what do you return?
  • Positions may repeat. What is the new lower bound, and does anything else break?
  • The positions are real numbers and you need the gap to within 1e-6. How do you bound the iterations?
  • Return the chosen positions, not just the gap.

Related questions

Related Topics