oneby7

Binary Search Searching the answer

249. Aggressive Cows

Hard

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

Output: 9

Explanation: 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

Output: 1

Explanation: 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

Output: 500000000

Explanation: 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.

stalls = [0, 2, 3, 6, 8, 12], k = 3

Constraints

  • 2 ≤ stalls.length ≤ 105
  • 0 ≤ stalls[i] ≤ 109
  • All the values in stalls are different.
  • 2 ≤ k ≤ stalls.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.