"""Pattern 17: Two heaps.

Split the data into a "small half" (max-heap) and a "large half" (min-heap),
keeping their sizes within one. The median is then at the top of one or both
heaps. The same two-heap shape solves "pick the best affordable option"
problems such as IPO.
"""

import heapq


class MedianFinder:
    def __init__(self) -> None:
        self.small: list[int] = []  # max-heap via negatives
        self.large: list[int] = []  # min-heap

    def add_num(self, num: int) -> None:
        heapq.heappush(self.small, -num)
        # Move the largest of the small half across so every small <= every large.
        heapq.heappush(self.large, -heapq.heappop(self.small))
        if len(self.large) > len(self.small):
            heapq.heappush(self.small, -heapq.heappop(self.large))

    def find_median(self) -> float:
        if len(self.small) > len(self.large):
            return float(-self.small[0])
        return (-self.small[0] + self.large[0]) / 2


def find_maximized_capital(k: int, w: int, profits: list[int], capital: list[int]) -> int:
    """IPO: projects sorted by required capital unlock into a max-heap of profits."""
    locked = sorted(zip(capital, profits))
    available: list[int] = []  # max-heap of profits (negatives)
    i = 0
    for _ in range(k):
        while i < len(locked) and locked[i][0] <= w:
            heapq.heappush(available, -locked[i][1])
            i += 1
        if not available:
            break
        w -= heapq.heappop(available)
    return w
