Got a TLE in the hostel visit problem. [Algo.Java]

Here’s my code - https://ide.codingblocks.com/s/233451

@lousybrick,
Try this question using Priority queue. It will easily pass the testcases.

1 Like

I’ve used a priority queue but this time my answer after 200 is coming as null and null.

@lousybrick,
Use long instead of int. And create an heap of size k. ArrayList< Integer> data here also use long instead of Integer.

I’m still getting the output as null. Here’s my code -

@lousybrick,
https://ide.codingblocks.com/s/233603 corrected code.

1 Like

Thank you! Could you explain briefly on how this approach works ?

@lousybrick,
in collections.reverseOrder we impose a reverse natural ordering on the elements on the priority queue. (or the max will be at the top)
if choice is 1
Now if the size of the queue is less than k add the distance to it. Else we remove the head of the queue and add the new element.

if choice is 2 we just print the top element.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.