A log pipeline needs the 10 slowest requests out of 100 million latency samples streaming past, without holding all 100 million in memory. Someone suggests a max-heap so the largest values are easy to find. What's actually the right structure, and why is a max-heap the wrong intuition here?
The question a top-10-largest algorithm actually needs to answer, over and over, is "is this new sample bigger than the smallest of the ten I'm currently keeping" — because that's the one comparison that decides whether a new sample deserves to bump something out of the current top ten. A min-heap of size 10 answers that in O(1): its defining property is that the smallest element is always at the root, ready to peek at with no search. A max-heap of size 10 would put the largest of the current top ten at its root, which answers a question nobody asked — "is this bigger than my current biggest" tells you almost nothing about whether it belongs in the top ten at all, since most new samples that belong in the top ten aren't bigger than the current single largest, they just need to beat the current smallest. PriorityQueue<Long> in Java is a min-heap by default (natural order, smallest first): keep pushing while it has fewer than 10 elements; once it has 10, compare each new sample against peek() (the current smallest of the ten), and only if the new one is bigger, remove the smallest and add the new one. The heap never grows past size 10, so memory is O(k) rather than O(n), and each sample costs O(log k) at worst — for k=10, four comparisons — instead of an O(n log n) full sort.