Skip to problem
←

Aggressive Cows

Hard 0 attempts

Given stall coordinates stalls on a line and a number of cows c, choose exactly c stalls, placing at most one cow in each.

Maximize the minimum distance between any two occupied stalls and return that distance. Once occupied coordinates are sorted, it is enough to consider gaps between adjacent cows.

Input coordinates may be unsorted. Each array entry represents a separate stall; if two chosen stalls have the same coordinate, their distance is zero. You may reorder the input array. Return only the optimal distance, not the chosen positions.

Function contract

Implement aggressiveCows(stalls, c).

Output: Return the largest achievable minimum distance between any two occupied stalls.

Example 1

Input
stalls = [1,2,4,8,9]
c = 3
Output
3

Explanation: Place cows at positions 1, 4, and 8. Their adjacent gaps are 3 and 4, so the minimum gap is 3. A minimum gap of 4 cannot accommodate all three cows.

Example 2

Input
stalls = [1,2]
c = 2
Output
1
Constraints
  • 2 <= stalls.length <= 100000
  • 0 <= stalls[i] <= 1000000000
  • 2 <= c <= stalls.length

Binary Search on Answer

Sort the coordinates. For a candidate distance, place the first cow at the leftmost stall, then place each next cow in the earliest stall far enough from the previous one. Choosing earlier positions leaves at least as much space for the remaining cows, so this greedy scan determines feasibility.

If a distance allows at least c cows, any smaller distance does too. Binary search for the largest feasible distance. An answer of zero is valid when separate stalls share coordinates.

javascript
function aggressiveCows(stalls, c) {
  stalls.sort((a,b)=>a-b);
  let lo = 1, hi = stalls[stalls.length-1] - stalls[0];
  while (lo <= hi) {
    const mid = Math.floor(lo + (hi-lo)/2);
    let cows = 1, last = stalls[0];
    for (let i = 1; i < stalls.length; i++) {
      if (stalls[i] - last >= mid) { cows++; last = stalls[i]; }
    }
    if (cows >= c) lo = mid + 1; else hi = mid - 1;
  }
  return hi;
}

Time: O(n log n + n log(D + 1)), where D is the coordinate range. Sorting is included.

Auxiliary space: O(1) for the search itself, plus the JavaScript sorting implementation’s workspace (commonly O(n)).

Loading discussion…

Saved in this browser only. Private to you.

JavaScript