NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior88 views

Место в кинотеатре максимально далеко от других зрителей (Maximize Distance to Closest Person) Условие: Места в кинотеатре расположены в один ряд и представлены массивом из нулей и единиц, где 1 — занятое место, 0 — свободное. Только что пришедший зритель выбирает свободное место так, чтобы расстояние до ближайшего уже сидящего зрителя было максимальным. Напишите функцию, которая возвращает это максимальное расстояние (в местах) от выбранного места до ближайшего занятого. Гарантируется, что в ряду есть хотя бы одно занятое место и хотя бы одно свободное. Входные данные: seats — массив из 0 и 1, длина от 2 до 10^5, содержит хотя бы одну 1 и хотя бы один 0. Выходные данные: Целое число — максимальное расстояние от выбранного места до ближайшего занятого.

Practice

AI answer

You can scan the array from left to right and account for half the gap between each pair of occupied seats. For the empty seats before the first occupied seat and after the last one, the distance is the length of the corresponding edge.

def max_distance(seats: list[int]) -> int:
    last = -1
    best = 0

    for i, seat in enumerate(seats):
        if seat == 1:
            if last == -1:
                best = i                 # empty edge at the beginning
            else:
                best = max(best, (i - last) // 2)
            last = i

    best = max(best, len(seats) - 1 - last)  # empty edge at the end
    return best

Within a gap, the maximum distance is reached roughly in the middle; at an edge, it is reached at the outermost empty seat. The time complexity is O(n), and the additional space complexity is O(1).

Also asked at getmatch agency

Similar questions