I'm solving a scheduling problem where each cow is milked from sáµ¢ to táµ¢ and needs báµ¢ buckets. Whenever a cow starts, it receives the smallest-numbered buckets that are currently available, and buckets are returned when milking ends. The goal is to find the total number of buckets needed.
For example, with cows (4,10,1), (8,13,3), and (2,6,2), the answer is 4.
My Python program sorts the cows by ending time and repeatedly scans them while advancing the current time. Initially, it entered an infinite loop because the loop condition depended on the list length, but the list was never shortened. After changing the code to mark completed cows with zeros, I still get incorrect results—for example, the sample produces 3 instead of 4. What is the issue with my approach, and what is a correct way to simulate or solve this problem?
4 Answers
You can solve this by building two events for every cow: `(sᵢ, +bᵢ)` and `(tᵢ, -bᵢ)`. Sort the events by time and maintain `current += change`; the largest value of `current` is the required number of buckets. The problem guarantees that all start and end times are distinct, so there is no tie-breaking issue. This runs in O(N log N), which is easily fast enough for N ≤ 100.
The larger issue is that sorting only by ending time and keeping one `bucket` count does not model the bucket labels correctly. When a cow starts, it receives the smallest available labels, so some buckets may remain occupied while lower-numbered buckets become free. You need to process all start and end events in chronological order, return buckets when a cow ends, and allocate the smallest available labels when another cow starts. Since the only quantity needed for the final answer is the maximum number of buckets in use at once, an event sweep is simpler: add báµ¢ at each start, subtract báµ¢ at each end, and track the largest running total.
The timeout happens because the loop condition never becomes false. If you use `while len(sorted_cows) != 0`, you must actually remove cows from the list. Setting their values to zero does not change the list length. Also, be careful not to modify a list while iterating over it, since that can cause skipped elements or index errors. A separate counter for completed cows, or filtering the list after processing, would avoid that problem.
I tried marking the entries as zero because removing them during iteration caused indexing problems, but I wasn’t sure how to make the loop stop once every cow had been processed.
Another straightforward option is to simulate time from 1 through 1000. At each time, first release buckets for cows whose milking ends, then allocate buckets for cows whose milking starts, and update the maximum currently in use. Because the time range is small, this is also efficient and avoids the complicated zeroing logic in the original code.

For the sample, the running totals are 2 at time 2, 3 at time 4, 1 after time 6, 4 at time 8, and 0 after time 13, so the maximum is 4.