Место в кинотеатре максимально далеко от других зрителей (Maximize Distance to Closest Person) Условие: Места в кинотеатре расположены в один ряд и представлены массивом из нулей и единиц, где 1 — занятое место, 0 — свободное. Только что пришедший зритель выбирает свободное место так, чтобы расстояние до ближайшего уже сидящего зрителя было максимальным. Напишите функцию, которая возвращает это максимальное расстояние (в местах) от выбранного места до ближайшего занятого. Гарантируется, что в ряду есть хотя бы одно занятое место и хотя бы одно свободное. Входные данные: seats — массив из 0 и 1, длина от 2 до 10^5, содержит хотя бы одну 1 и хотя бы один 0. Выходные данные: Целое число — максимальное расстояние от выбранного места до ближайшего занятого.
Asked at
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
- Why did you leave your previous job?
- What types of data are there in Python?
- Tell us about your work experience.
- A user uploads a video and selects the desired processing, which he wants to get. The service accepts the video, applies the necessary processing, and outputs the final result. By processing, we can understand, for example, the following: make the video black and white, flip it, speed it up N times, etc. It is important that the user can monitor the progress of the processing. Load: 10,000 videos per minute
- What frameworks have you worked with?
Similar questions
- Given an integer array `nums` sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] Constraints: - 1 <= nums.length <= [phone] <= nums[i] <= 104 - `nums` is sorted in non-decreasing order.
- Maximum length of consecutive ones after deleting one element (Max Consecutive Ones After Deleting One Element) Condition: Given a non-empty array consisting of only zeros and ones. Find the maximum length of consecutive ones that can be obtained by deleting exactly one element from the array. Deleting one element is mandatory, even if the array consists entirely of ones. Input data: - nums – a non-empty array of integers, each element is 0 or 1 Output: - An integer – the maximum length of consecutive ones after deleting exactly one element Constraints: - 1 <= nums.length <= 10^5 - nums[i] is 0 or 1 Example: Go code: ```go // Available without import: sort, fmt, encoding/json package main func MaxOnes(nums []int) int { // TODO: write solution here return 0 } ``` Python code: ```python # Available without import: json, sys, io def max_ones(nums): # TODO: write solution here return 0 ```
- Return the index of an element in a sorted array that has been cyclically shifted, or -1 if the element is not found. For example, given the array [4, 5, 6, 7, 0, 1, 2], searching for 0 should return 4, while searching for 3 should return -1.
- Write code to print each number and its count in an array if the number appears more than once.
- Given two vectors, size N. Each of N users is described by a set of numerical features — vectors of dimension M. Task: find which users are most similar to each other.