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?- A. 4
- B. 3
- C. 2
- 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
- Problem: Trains arrive at times [900, 940, 950, 1100, 1500, 1800] and depart at [910, 1200, 1120, 1130, 1900, 2000]. The two-pointer code…
- Problem: Return, for each index i, the product of all other elements (no division allowed). Print the list for a = [2, 3, 4, 5]. python a…
- Problem: How many distinct non-empty substrings does the string 'abab' contain? python s = 'abab' print(len({s[i:j] for i in range(len(s))…
- Problem: What is the maximum XOR of any two different elements of the array [3, 10, 5, 25, 2, 8]? python a = [3, 10, 5, 25, 2, 8]…
- Problem: What is the length of the longest contiguous subarray containing at most two distinct values? python from collections import…
- Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order…