Binary Search Searching the answer
249. Aggressive Cows
A barn has a row of stalls along one straight wall. stalls[i] is the position of stall i along that wall.
You have k cows to put in the barn, one cow per stall. The cows get aggressive when they stand close to each
other, so you want them spread out.
For a placement of the cows, look at the two cows that stand closest together. Place the k cows so that
these two are as far apart as possible, and return that distance. The distance between two cows is the
difference between the positions of their stalls.
Example 1
Input: stalls = [10, 3, 17, 1, 8, 25], k = 3
9Explanation: Put the cows at 1, 10 and 25. They are 9 and 15 apart, so the closest two are 9 apart. With the middle cow at 8 or 17 instead, the closest two would be only 7 or 8 apart.
Example 2
Input: stalls = [5, 0, 4, 9, 1], k = 4
1Explanation: Only one stall stays empty. The stalls at 0 and 1 are 1 apart, and so are the stalls at 4 and 5. One empty stall can split up only one of these pairs, so two cows always end up 1 apart.
Example 3
Input: stalls = [0, 500000000, 499999999, 1000000000, 2]
k = 3
500000000Explanation: Put the cows at both ends and at 5 × 108, exactly halfway. Each cow is 5 × 108 from its neighbour.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
2 ≤ stalls.length ≤ 1050 ≤ stalls[i] ≤ 109- All the values in
stallsare different. 2 ≤ k ≤ stalls.length
Clarifying questions
What you would ask an interviewer before writing any code.