Assign Mice to Holes - GeeksforGeeks

31 Mar, 2021
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.
Examples: 
Input : positions of mice are:
          4 -4 2
        positions of holes are:
          4 0 5
Output :  4
Assign mouse at position x = 4 to hole at 
position x = 4 : Time taken is 0 minutes 
Assign mouse at position x=-4 to hole at 
position x = 0 : Time taken is 4 minutes 
Assign mouse at position x=2 to hole at 
position x = 5 : Time taken is 3 minutes 
After 4 minutes all of the mice are in the holes.
Since, there is no combination possible where
the last mouse's time is less than 4, 
answer = 4.

Input :  positions of mice are:
        -10, -79, -79, 67, 93, -85, -28, -94 
          positions of holes are:
         -2, 9, 69, 25, -31, 23, 50, 78 
Output : 102
This problem can be solved using greedy strategy. We can put every mouse to its nearest hole to minimize the time. This can be done by sorting the positions of mice and holes. This allows us to put the ith mice to the corresponding hole in the holes list. We can then find the maximum difference between the mice and corresponding hole position. 
In example 2, on sorting both the lists, we find that the mouse at position -79 is the last to travel to hole 23 taking time 102.
sort mice positions (in any order)
sort hole positions 

Loop i = 1 to N:
    update ans according to the value 
    of |mice(i) - hole(i)|. It should
    be maximum of all differences.
Proof of correctness: Let i1 < i2 be the positions of two mice and let j1 < j2 be the positions of two holes. It suffices to show via case analysis that 
max(|i1-j1|, |i2-j2|) <= max(|i1-j2|, |i2-j1|), 
   where '|a - b|' represent absolute value of (a - b)
Since it follows by induction that every assignment can be transformed by a series of swaps into the sorted assignment, where none of these swaps increases the span. 
C++
Java
Python3
C#
Javascript
// C++ program to find the minimum// time to place all mice in all holes.#include <bits/stdc++.h>using namespace std; // Returns minimum time required// to place mice in holes.int assignHole(int mices[], int holes[],               int n, int m){         // Base Condition    // No. of mouse and holes should be same    if (n != m)        return -1;         // Sort the arrays    sort(mices, mices + n);    sort(holes, holes + m);         // Finding max difference between    // ith mice and hole    int max = 0;    for(int i = 0; i < n; ++i)    {        if (max < abs(mices[i] - holes[i]))            max = abs(mices[i] - holes[i]);    }    return max;} // Driver Codeint main(){         // Position of mouses     int mices[] = { 4, -4, 2 };       // Position of holes    int holes[] = { 4, 0, 5 };       // Number of mouses    int n = sizeof(mices) / sizeof(mices[0]);       // Number of holes    int m = sizeof(holes) / sizeof(holes[0]);       // The required answer is returned    // from the function    int minTime = assignHole(mices, holes, n, m);       cout << "The last mouse gets into the hole in time:"         << minTime << endl;       return 0;} // This code is contributed by Aayush Garg
// Java program to find the minimum time to place// all mice in all holes.import java.util.* ; public class GFG{    // Returns minimum time required to place mice    // in holes.    public int assignHole(ArrayList<Integer> mice,                         ArrayList<Integer> holes)    {        if (mice.size() != holes.size())           return -1;         /* Sort the lists */        Collections.sort(mice);        Collections.sort(holes);         int size = mice.size();         /* finding max difference between ith mice and hole */        int max = 0;        for (int i=0; i<size; i++)            if (max < Math.abs(mice.get(i)-holes.get(i)))                max = Math.abs(mice.get(i)-holes.get(i));         return Math.abs(max);    }     /* Driver Function to test other functions */    public static void main(String[] args)    {        GFG gfg = new GFG();        ArrayList<Integer> mice = new ArrayList<Integer>();        mice.add(4);        mice.add(-4);        mice.add(2);        ArrayList<Integer> holes= new ArrayList<Integer>();        holes.add(4);        holes.add(0);        holes.add(5);        System.out.println("The last mouse gets into "+         "the hole in time: "+gfg.assignHole(mice, holes));    }}
# Python3 program to find the minimum# time to place all mice in all holes. # Returns minimum time required# to place mice in holes.def assignHole(mices, holes, n, m):         # Base Condition    # No. of mouse and holes should be same    if (n != m):        return -1         # Sort the arrays    mices.sort()    holes.sort()         # Finding max difference between    # ith mice and hole    Max = 0         for i in range(n):        if (Max < abs(mices[i] - holes[i])):            Max = abs(mices[i] - holes[i])         return Max     # Driver code    # Position of mousesmices = [ 4, -4, 2 ] # Position of holesholes = [ 4, 0, 5 ] # Number of mousesn = len(mices) # Number of holesm = len(holes) # The required answer is returned# from the functionminTime = assignHole(mices, holes, n, m) print("The last mouse gets into the hole in time:", minTime) # This code is contributed by divyeshrabadiya07
// C# program to find the minimum// time to place all mice in all holes.using System;class GFG{         // Returns minimum time required    // to place mice in holes.    static int assignHole(int[] mices, int[] holes,                   int n, int m)    {                  // Base Condition        // No. of mouse and holes should be same        if (n != m)            return -1;                  // Sort the arrays        Array.Sort(mices);        Array.Sort(holes);                  // Finding max difference between        // ith mice and hole        int max = 0;        for(int i = 0; i < n; ++i)        {            if (max < Math.Abs(mices[i] - holes[i]))                max = Math.Abs(mices[i] - holes[i]);        }        return max;    }     // Driver code      static void Main()  {         // Position of mouses     int[] mices = { 4, -4, 2 };         // Position of holes    int[] holes = { 4, 0, 5 };         // Number of mouses    int n = mices.Length;         // Number of holes    int m = holes.Length;         // The required answer is returned    // from the function    int minTime = assignHole(mices, holes, n, m);    Console.WriteLine("The last mouse gets into the hole in time: " + minTime);  }} // This code is contributed by divyesh072019
<script>    // Javascript program to find the minimum    // time to place all mice in all holes.         // Returns minimum time required    // to place mice in holes.    function assignHole(mices, holes, n, m)    {         // Base Condition        // No. of mouse and holes should be same        if (n != m)            return -1;         // Sort the arrays        mices.sort();        holes.sort();         // Finding max difference between        // ith mice and hole        let max = 0;        for(let i = 0; i < n; ++i)        {            if (max < Math.abs(mices[i] - holes[i]))                max = Math.abs(mices[i] - holes[i]);        }        return max;    }         // Position of mouses    let mices = [ 4, -4, 2 ];        // Position of holes    let holes = [ 4, 0, 5 ];        // Number of mouses    let n = mices.length;        // Number of holes    let m = holes.length;        // The required answer is returned    // from the function    let minTime = assignHole(mices, holes, n, m);        document.write("The last mouse gets into the hole in time:" + minTime);          // This code is contributed by mukesh07.</script>
The last mouse gets into the hole in time: 4
 This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
aayushgarg06
divyeshrabadiya07
divyesh072019
mukesh07
Greedy
Mathematical
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Job Sequencing Problem
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples