Problem
There are N
mice and N
holes are placed in a straight line. Each hole can accommodate only 1 mouse. A mouse can stay at his position, move one step right from x
to x + 1
, or move one step left from x
to x − 1
. Any of these moves consumes 1 minute. Assign mice to holes so that the time when the last mouse gets inside a hole is minimized(i.e., minimize the maximum time taken by any mouse).
Input
A
: List of positions of mice (length N)B
: List of positions of holes (length N)
Output
- Single integer: the minimum time when the last mouse gets inside a hole
Note: The final answer will fit in a 32-bit signed integer.
Examples
Example 1
|
|
Solution
Method 1 - Greedy Matching
This is a greedy matching problem. To minimize the maximum time, sort both the mice and holes positions. Assign the ith mouse to the ith hole. The answer is the maximum absolute difference between the positions of each assigned pair.
Why does this work? Sorting ensures that the largest gaps are minimized, and no better assignment can improve the maximum distance for any mouse.
Code
Java
|
|
Python
|
|
Complexity
- ⏰ Time complexity:
O(N log N)
— Sorting both arrays takes O(N log N), and the final loop is O(N). - 🧺 Space complexity:
O(1)
— Sorting can be done in-place; only a few variables are used.