Pattern
Pattern
Pattern
Keep only the most important candidates with a priority queue.
Choose min-heap or max-heap based on which candidate should leave first.
import heapq
heap = []
for value in nums:
heapq.heappush(heap, value)
if len(heap) > k:
heapq.heappop(heap)
top_k = sorted(heap, reverse=True)