def longest_balanced_segment(changes: list[int]) -> int:
    """Return the longest contiguous segment with total change zero.

    Args:
        changes: Signed integer changes, including an empty list.

    Returns:
        The longest qualifying length, or zero when none exists.
    """
    first_position = {0: -1}
    total = 0
    longest = 0
    for index, change in enumerate(changes):
        total += change
        if total in first_position:
            longest = max(longest, index - first_position[total])
        else:
            first_position[total] = index
    return longest


for changes in ([3, -1, -2, 5, -5, 4], [], [0, 0], [1, 2],
                [2, -2, 2, -2]):
    print(changes, longest_balanced_segment(changes))

import heapq


def required_instruments(runs: list[tuple[int, int]]) -> int:
    """Return the minimum instruments needed for fixed run intervals.

    Args:
        runs: Integer half-open intervals in any order.

    Returns:
        The maximum number of simultaneously active runs.

    Raises:
        ValueError: If an interval has nonpositive duration.
    """
    if any(end <= start for start, end in runs):
        raise ValueError("Every run must have positive duration.")
    active_ends = []
    peak = 0
    for start, end in sorted(runs):
        while active_ends and active_ends[0] <= start:
            heapq.heappop(active_ends)
        heapq.heappush(active_ends, end)
        peak = max(peak, len(active_ends))
    return peak


for runs in ([(0, 4), (1, 3), (3, 6), (6, 7)], [],
             [(0, 2), (2, 4)], [(0, 2), (0, 2), (0, 2)]):
    print(runs, required_instruments(runs))

def shared_signal_length(first: list[int], second: list[int]) -> int:
    """Return the longest identical contiguous block length.

    Args:
        first: First sequence of integer sensor states.
        second: Second sequence of integer sensor states.

    Returns:
        The longest shared block length, or zero when no block exists.
    """
    if not first or not second:
        return 0
    previous = [0] * (len(second) + 1)
    longest = 0
    for first_value in first:
        current = [0] * (len(second) + 1)
        for column, second_value in enumerate(second, start=1):
            if first_value == second_value:
                current[column] = previous[column - 1] + 1
                longest = max(longest, current[column])
        previous = current
    return longest


for first, second in (([4, 1, 2, 3, 8], [9, 1, 2, 3, 7]),
                      ([1, 2, 3], [1, 9, 3]), ([], [1]),
                      ([2, 2, 2], [2, 2])):
    print(first, second, shared_signal_length(first, second))
