Module 5 · Heaps · Applications of Heap

Kth largest element

Keep only the k largest values seen so far, in a min heap. Its root is the smallest of them — the k-th largest — so a new number only gets in if it beats the root, and the heap never grows past k.

topKElements is a PriorityQueue (min heap) of the k largest values so far.