Hostel Visit Heaps

import java.util.*;
public class Main{

public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int T = sc.nextInt();
	int k = sc.nextInt();
	ArrayList<Integer> list = new ArrayList<>();
	while(T--!=0) {
		int q = sc.nextInt();
		if(q==1) {
			int x = sc.nextInt();
			int y = sc.nextInt();
			
			int d = (x*x  + y*y);
			list.add(d);
		}
		if(q==2) {
			PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
			for(int i=0;i<list.size();i++) {
				pq.add(list.get(i));
			}
			for(int i=k;i<list.size();i++) {
				if(list.get(i)<pq.peek()) {
					pq.poll();
					pq.add(list.get(i));
				}
			}
			System.out.println(pq.peek());
		
	}
}

}}

//sir when I’m running this code on eclipse I’m getting the correct output but when I’m compiling in CB ide I’m getting Time Limit exceeded please suggest any changes to the code

@Siddharth_sharma1808
You are creating a new PQ everytime and pushing elements into it for each query. This will increase the time complexity. Instead create a PQ before the queries even start. Make it of size k i.e. its size should remain atmost k at any instance. Make sure it is max heap.
Think about this approach and try it out. Let me know if you need more hints.

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.