public class KthLargest {
private readonly PriorityQueue<int, int> pq = new();
private readonly int k;
public KthLargest(int k, int[] nums) {
this.k = k;
foreach (int x in nums)
InsertAndTrim(x);
}
public int Add(int val) {
InsertAndTrim(val);
return pq.Peek();
}
private void InsertAndTrim(int x) {
pq.Enqueue(x, x);
if (pq.Count > k) pq.Dequeue();
}
}Min Heap for Kth largest pattern.
We insert in the heap, and if heap is greater than k, we remove minimum element. This way, we always have K largest elements in the heap, and the top node is exactly the Kth largest since this is a min heap.