Data Structures & AlgorithmsHardCodeforces Div2 C · binary search on answer

Problem: Cows must be placed in stalls at positions [1, 2, 4, 8, 9] so that the minimum distance between any two cows is as large as possible. With 3 cows, what is that maximum minimum distance? Use binary search on the answer.

Problem: Cows must be placed in stalls at positions [1, 2, 4, 8, 9] so that the minimum distance between any two cows is as large as possible. With 3 cows, what is that maximum minimum distance? Use binary search on the answer.
def can(pos, cows, d):
    c, last = 1, pos[0]
    for p_ in pos[1:]:
        if p_ - last >= d:
            c += 1
            last = p_
    return c >= cows
def solve(pos, cows):
    pos = sorted(pos)
    lo, hi = 0, pos[-1] - pos[0]
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if can(pos, cows, mid):
            lo = mid
        else:
            hi = mid - 1
    return lo
print(solve([1, 2, 4, 8, 9], 3))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 2
  4. D. 5

Correct answer: B. 3

A distance of 3 is achieved by stalls 1, 4, 8 (gaps 3 and 4). A distance of 4 needs three stalls spaced at least 4 apart, which is impossible here.

More Coding Interview Problems questions

Exams that ask this topic