Program to find maximum distance between empty and occupied seats in Python

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a list with only 0s and 1s called seats. Where seats[i] represents a seat. When it is 1, then it is occupied, otherwise free. There is at least one free seat and at least one occupied seat, we have to find the maximum distance from a free seat to the nearest occupied seat.

So, if the input is like seats = [1, 0, 1, 0, 0, 0, 1], then the output will be 2, because we can occupy seat seats[4], then distance is 2.

To solve this, we will follow these steps −

• res := 0

• last := -1

• n := size of seats

• for i in range 0 to n - 1, do

• if seats[i] is 1, then

• res := maximum of res and (i if last < 0 otherwise floor of (i-last)/2)

• last := i

• return maximum of res and (n-last-1)

Example

Let us see the following implementation to get better understanding

def solve(seats):
res, last, n = 0, -1, len(seats)
for i in range(n):
if seats[i]:
res = max(res, i if last < 0 else (i - last) // 2)
last = i
return max(res, n - last - 1)

seats = [1, 0, 1, 0, 0, 0, 1]
print(solve(seats))

Input

[1, 0, 1, 0, 0, 0, 1]


Output

2
Updated on 12-Oct-2021 11:03:21