"""Pattern 15: Top K elements with a heap.

Keep a heap of size k. For the k LARGEST items use a MIN-heap: its root is
the smallest of the current top k, so anything bigger replaces it. That is
O(n log k) time and O(k) space, better than sorting when k is small.
"""

import heapq
from collections import Counter


def kth_largest(nums: list[int], k: int) -> int:
    heap: list[int] = []
    for x in nums:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:
            heapq.heapreplace(heap, x)
    return heap[0]


def top_k_frequent(nums: list[int], k: int) -> list[int]:
    """The k most frequent values, most frequent first."""
    counts = Counter(nums)
    return heapq.nlargest(k, counts, key=counts.__getitem__)


def k_closest(points: list[list[int]], k: int) -> list[list[int]]:
    """k points closest to the origin (squared distance avoids sqrt)."""
    return heapq.nsmallest(k, points, key=lambda p: p[0] * p[0] + p[1] * p[1])


def last_stone_weight(stones: list[int]) -> int:
    """Python's heapq is a min-heap; push negatives to simulate a max-heap."""
    heap = [-s for s in stones]
    heapq.heapify(heap)
    while len(heap) > 1:
        a = -heapq.heappop(heap)
        b = -heapq.heappop(heap)
        if a != b:
            heapq.heappush(heap, -(a - b))
    return -heap[0] if heap else 0
