hardBinary SearchGreedyBinary Search

Aggressive Cows

hardTime: O(n log(max-min))Space: O(1)

Recognize the pattern

place cows in stalls maximizing minimum distancebinary search on distancegreedy placement check

Brute force idea

Try all combinations of stalls — C(n,k). Combinatorial.

Better approach

Sort stalls. Binary search on the answer (minimum distance). For each candidate, greedily place cows: put cow in first stall, then next stall ≥ current + distance. If all cows placed, distance works. O(n log range).

Key invariant

If distance d works (can place all cows), any d' < d also works. This monotonicity validates binary search. Greedy placement is optimal — starting from the leftmost stall and placing as early as possible maximizes remaining room.

Watch out for

Not sorting stalls first — the greedy placement only works on sorted positions.

Binary Search Pattern