You have N(<201) tables for costumers. M(<401) constumers will place orders. Each customer will place an order and if he is not already seated, a table will be cleaned and will be given to him. If no tables are empty some customer(of your choice) will be asked to leave and the new costumer will be placed on the empty table after cleaning. You are given the sequence in which customers place their orders. Find the minimum number of tables that must be cleaned.
EXPLANATION:
Let’s say a customer comes with an order:
If he is already seated, do nothing. We don’t have to clean a table.
If not seated, two cases arrive:
Empty table is available: We clean the table and give a table to him. Any empty table will work.
No empty table is available: We have to remove someone from the table. We would prefer to remove someone who doesn’t places an order in future. If such customers are seated, we can remove anyone from them. If we remove someone who will order in future, we’ll have to clean one extra table which we won’t have to if we pick greedily. If no such customer is present who’ll NOT order in future, we’ll pick a customer who will order in future in farthest of time. This will ensure that minimum number of swaps are to be made.
Once the greedy approach is clear, implementation is very easy. It can be solved in O(N*M). Using heaps/priority queue we can also solve in O(N log M).
In 2nd case, when no tables are available, what if we ask that particular customer to leave, who will be giving the order least number of times after that? Why choose someone who will give the order farthest in time? Can you prove why it is correct?
In 2nd case, when no tables are available, what if we ask that particular customer to leave, who will be giving the order least number of times after that? Why choose someone who will give the order farthest in time? Can you prove why it is correct?
@ ketanhwr Thumbs up! I’ve done the same way.
@ Editorialist I don’t know if I can ask this here. Can you give me a test case which differentiates your approach with the one mentioned by ketanhwr ?
The solution wont work because there may be a case where a person will order once more after 1 second, and another will order 10 more times all after 3,4,5… seconds. Your algo will kick out the first guy, then reinvite, then kick him out again. Thats 3 tasks instead of the optimal 1 task. I have posted the odd test case.
Shouldn’t it be “If no such customer is present who’ll NOT order in future, we’ll pick a customer who will order in future in farthest of time.”? Or did I not understand that statement correctly?
Even I implemented the same Optmal age Replacemennt Algo, and for commented test cases too its working correctly. Can somebody tell me where I am wrong.