Aggressive cows
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
You must place a fixed number of things along a line so that the closest two are as far apart as possible. You guess a minimum gap, greedily check whether everything fits, and halve the range of gaps until you find the best one.
Practical use cases
- Web app: Placing pickup lockers along a street map. A delivery app must open 4 pickup points among 20 possible shops along a road so that customers are spread out evenly. The planner guesses a minimum gap of 3 km, places points greedily, and sees whether 4 fit. Halving the guess finds the widest possible gap in a few tries.
- Web app: Spacing ads on a feed. A social feed must show 5 ads among 200 allowed positions, as far apart as possible so users do not see them bunched together. Checking a guessed gap is one quick pass, and the best spacing is found in about 8 guesses.
- System: Radio towers and ATMs. Telecom and banking planners choose a few sites from many candidate locations so that the closest two are as far apart as possible, to cover more ground. Without this approach the team would have to test combinations by hand.
The story: Cows Who Do Not Get Along
Farmer Hari had a row of stalls at positions 1, 2, 4, 8 and 9 on the number line of his shed, and three cows that hated each other. If two cows stood close, they butted heads. "Put one cow in each of three stalls," he said, "so that the closest pair of cows is as far apart as possible."
Mira did not try every combination. She guessed the gap: "Can I keep every pair at least 5 apart?" Greedy check: first cow at stall 1; the next stall at least 5 away is 8; the next at least 5 beyond 8 does not exist. Only two cows fit, so a gap of 5 is too ambitious. "Can I keep them 3 apart?" Cows at 1, 4 and 8: yes, 3 cows!
The pattern is the one from binary search on the answer: if a gap of 3 works, any smaller gap works too, and if 5 fails, any bigger one fails. So she halved the possible gaps (1 to 8). Test the middle gap with the greedy check; if it works, try bigger; if not, try smaller. A gap of 3 was the best. A few guesses replaced hundreds of seating plans.
How to spot this problem, and where you need it
You must choose some positions from many options and want the smallest gap between any two chosen ones to be as large as it can be.
Signs you need it
- The problem says "maximise the minimum distance", "place k items", "as far apart as possible" or "aggressive cows".
- Positions are on a line, sorted or sortable, and you must pick exactly k of them.
- Trying all combinations of picks is hopeless because the number of combinations explodes.
Where to use it in a project
- Spreading stores, warehouses, chargers or ad slots as evenly as possible on a route or feed.
- Seating, scheduling or sensor placement where neighbours need a safe distance.
The solution
Sort the positions. The answer is a gap between 1 and the full length. Guess a gap in the middle. Check it greedily: place the first item at the start, then put the next at the first position at least that far away, and so on. If you place all k, the gap works, so try bigger; otherwise try smaller. Repeat until the range closes.
Payoff: Before: trying millions of ways to choose positions. After: about 20 guesses, each a single quick pass.
Explain it like I am 8
You have 3 grumpy friends and some seats in a row. You want them sitting as far apart as possible. Guess a distance, like "at least 3 seats apart". Put the first friend at the start, then the next friend at the first seat that is far enough. If everybody found a seat, the distance works and you can try a bigger one!
How it works, step by step
- Sort the stall positions. The gap can be as small as 1 and at most
last - first. - Write the check: put the first cow in the first stall; walk along and put the next cow in the first stall at least
gapaway from the last cow. - If you can place all the cows, that gap works: remember it as
bestand try a bigger gap (low = mid + 1). - If you cannot place them all, the gap is too big:
high = mid - 1. - When low passes high,
bestis the largest possible minimum gap.
The code in four languages
PHP
<?php
// Can we place $cows cows so every two are at least $gap apart? (stalls are sorted)
function canPlace(array $stalls, int $cows, int $gap): bool {
$placed = 1; // first cow goes in the first stall
$last = $stalls[0];
for ($i = 1; $i < count($stalls); $i++) {
if ($stalls[$i] - $last >= $gap) {
$placed++; // far enough: place a cow here
$last = $stalls[$i];
if ($placed >= $cows) return true;
}
}
return $placed >= $cows;
}
// Largest possible value of the smallest distance between any two cows.
function aggressiveCows(array $stalls, int $cows): int {
sort($stalls);
$low = 1;
$high = $stalls[count($stalls) - 1] - $stalls[0];
$best = 0;
while ($low <= $high) {
$mid = intdiv($low + $high, 2);
if (canPlace($stalls, $cows, $mid)) {
$best = $mid; // this gap works: try a bigger one
$low = $mid + 1;
} else {
$high = $mid - 1; // too ambitious: try smaller
}
}
return $best;
}
echo aggressiveCows([1, 2, 4, 8, 9], 3), "\n"; // 3
echo aggressiveCows([10, 1, 2, 7, 5], 3), "\n"; // 4JavaScript
// Can we place cows so every two are at least "gap" apart? (stalls are sorted)
function canPlace(stalls, cows, gap) {
let placed = 1; // first cow goes in the first stall
let last = stalls[0];
for (let i = 1; i < stalls.length; i++) {
if (stalls[i] - last >= gap) {
placed++; // far enough: place a cow here
last = stalls[i];
if (placed >= cows) return true;
}
}
return placed >= cows;
}
// Largest possible value of the smallest distance between any two cows.
function aggressiveCows(stalls, cows) {
stalls = [...stalls].sort((a, b) => a - b);
let low = 1;
let high = stalls[stalls.length - 1] - stalls[0];
let best = 0;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (canPlace(stalls, cows, mid)) {
best = mid; // this gap works: try a bigger one
low = mid + 1;
} else {
high = mid - 1; // too ambitious: try smaller
}
}
return best;
}
console.log(aggressiveCows([1, 2, 4, 8, 9], 3)); // 3
console.log(aggressiveCows([10, 1, 2, 7, 5], 3)); // 4Java
import java.util.*;
public class Main {
// Can we place cows so every two are at least "gap" apart? (stalls are sorted)
static boolean canPlace(int[] stalls, int cows, int gap) {
int placed = 1; // first cow goes in the first stall
int last = stalls[0];
for (int i = 1; i < stalls.length; i++) {
if (stalls[i] - last >= gap) {
placed++; // far enough: place a cow here
last = stalls[i];
if (placed >= cows) return true;
}
}
return placed >= cows;
}
// Largest possible value of the smallest distance between any two cows.
static int aggressiveCows(int[] input, int cows) {
int[] stalls = input.clone();
Arrays.sort(stalls); // the stalls must be in order first
int low = 1;
int high = stalls[stalls.length - 1] - stalls[0];
int best = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
if (canPlace(stalls, cows, mid)) {
best = mid; // this gap works: try a bigger one
low = mid + 1;
} else {
high = mid - 1; // too ambitious: try smaller
}
}
return best;
}
public static void main(String[] args) {
System.out.println(aggressiveCows(new int[]{1, 2, 4, 8, 9}, 3)); // 3
System.out.println(aggressiveCows(new int[]{10, 1, 2, 7, 5}, 3)); // 4
}
}Go
package main
import (
"fmt"
"slices"
)
// canPlace: can we place cows so every two are at least gap apart? (stalls are sorted)
func canPlace(stalls []int, cows, gap int) bool {
placed := 1 // first cow goes in the first stall
last := stalls[0]
for _, s := range stalls[1:] {
if s-last >= gap {
placed++ // far enough: place a cow here
last = s
if placed >= cows {
return true
}
}
}
return placed >= cows
}
// aggressiveCows returns the largest possible value of the smallest distance between any two cows.
func aggressiveCows(input []int, cows int) int {
stalls := slices.Clone(input)
slices.Sort(stalls) // the stalls must be in order first
low := 1
high := stalls[len(stalls)-1] - stalls[0]
best := 0
for low <= high {
mid := low + (high-low)/2
if canPlace(stalls, cows, mid) {
best = mid // this gap works: try a bigger one
low = mid + 1
} else {
high = mid - 1 // too ambitious: try smaller
}
}
return best
}
func main() {
fmt.Println(aggressiveCows([]int{1, 2, 4, 8, 9}, 3)) // 3
fmt.Println(aggressiveCows([]int{10, 1, 2, 7, 5}, 3)) // 4
}Time: O(n log n + n log D) · Extra space: O(1). Sort once, then about log D guesses (D = the distance between the first and last stall), each check scanning n stalls.
Watch out for
- Forgetting to sort the stalls; the greedy check only works left to right.
- Searching for the smallest working gap instead of the largest. Here a working gap means "try bigger".
- Placing the first cow anywhere but the first stall; the first stall is always at least as good.
Quick check
- What are we maximising?
- The smallest gap between any two cows
- The number of cows
- The sum of gaps
- If a gap of 3 lets all cows fit, what do we try next?
- A bigger gap
- A smaller gap
- Stop immediately
- Why is the check greedy?
- Putting each cow as early as possible leaves the most room for the rest
- It is faster to code
- Cows like the left side