import heapq


def k_closest_elaborated(points: list[list[int]], K: int) -> list[list[int]]:
    """K-closest by maintaining a K-sized max heap

    Since a max heap allows us to fetch the furthest distance in constant-time,
    once we build up a K-sized heap, we can maintain size K by only considering
    points with distances better than the furthest known distance. If a point
    does meet this criterion, we pop off the max-distanced point in the heap and
    push the new point.

    Complexity:
        K = len(heap)
            Time: O(NlogK) N heap push/pop operations on heap with size ≤ K
            Space: O(K) priority queue of size K

    Args:
        points:
        K:

    Returns: K-closest points to the origin

    Examples:
        >>> k_closest_elaborated([[1,3],[-2,2]],1)
        [[-2, 2]]
        >>> k_closest_elaborated([[3,3],[5,-1],[-2,4]],2)
        [[-2, 4], [3, 3]]

    """

    """ALGORITHM"""
    ## INITIALIZE VARS ##
    max_heap = []

    for point in points:
        # negate to use minheap as a maxheap
        dist = -sum(coord ** 2 for coord in point)
        dist_and_point = (dist, point)

        # maintain a max_heap of size ≤ K
        if len(max_heap) < K:
            heapq.heappush(max_heap, dist_and_point)
        else:
            # if current point's distance is better
            #   pop point with worst distance
            #   and push current point
            # else
            #   noop
            _ = heapq.heappushpop(max_heap, dist_and_point)

    return [point for (dist, point) in max_heap]