2024 December Bronze · "Walking the Cows"

← All past problems · Official statement

The premise

Farmer John has N cows, each scheduled to be walked at a specific time. Cows can be walked in groups, but a group can only contain cows whose appointment times are within K minutes of each other. Each group takes a fixed amount of time. Compute the minimum number of groups needed to walk every cow on time.

(Wording paraphrased — see official PDF for the exact statement, constraints, and sample inputs.)

Constraints

Key idea

Sort, then greedy-sweep. Once times are sorted, the optimal grouping always extends a group as far as it can go before starting a new one. Each cow either fits in the current group's [start, start+K] window or starts a new group.

Why greedy works: any cow you delay would only fit into a later group, never an earlier one, so extending the current group is always safe.

Pseudocode

read N, K, t[1..N]
sort(t)
groups = 0
start = -INF
for i in 1..N:
    if t[i] > start + K:
        groups += 1
        start  = t[i]
print(groups)

Complexity

Sorting dominates at O(N log N). The sweep is O(N). Trivially fast at N = 10⁵.

Pitfalls

What to take away