Problem Description
We are given positions of hens and grains on a one‐dimensional line. A hen can eat any grain instantly if they are at the same position, and a hen can eat multiple grains. In one second, a hen can move to an adjacent position (left or right by 1 unit) and all hens move simultaneously and independently. The task is to determine the minimum time needed such that, if the hens move optimally, all grains are eaten.
Key Insights
- Sort both the hens and grains arrays to simplify greedy assignment.
- Use binary search on the answer (time T) to find the minimum T for which an assignment is possible.
- For a given T, check feasibility by iterating over hens and greedily assigning as many contiguous grains as possible to each hen.
- For one hen at position p covering grains in a contiguous segment [L, R], the required time is computed as: min(|p - L| + (R - L), |p - R| + (R - L)) – this captures the optimal route when the hen must cover both extremes.
- If all grains can be assigned to some hen within T seconds, then T is feasible.
Space and Time Complexity
Time Complexity: O((n + m) * log(max_coordinate)) where n and m are the number of hens and grains respectively, and max_coordinate is the range of positions.
Space Complexity: O(n + m) due to the need to store sorted arrays (if the input is to be copied).
Solution
The solution uses a binary search to decide on the minimum time T required. For each candidate time T, the algorithm checks if it is possible to assign all grains to the hens such that each hen can cover its assigned contiguous block of grains within T seconds. This checking function works as follows:
- Sort both the hens and grains arrays.
- Initialize a pointer for the grains array.
- For each hen (in sorted order), try to cover as many consecutive grains as possible:
- For the starting grain in the current segment, let L = current grain’s position.
- Increase the pointer for the current hen while for the current grain “R” in the segment, the condition min(|p - L| + (R - L), |p - R| + (R - L)) ≤ T holds (where p is the hen’s position). This condition determines whether the hen can travel to L and R (in either order) within time T.
- If all grains are covered after iterating over all hens, T is a feasible candidate.
- Use binary search to minimize T.
The main trick is carefully checking the travel time cost for covering a block of grains using a greedy method and then optimizing over T with binary search.