- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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)

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))

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

2

- Related Questions & Answers
- Find maximum distance between any city and station in Python
- Program to find maximum distance between a pair of values in Python
- Find maximum distance between any city and station in C++
- Program to find minimum total distance between house and nearest mailbox in Python
- Program to find distance of shortest bridge between islands in Python
- Find the maximum distance covered using n bikes in Python
- Program to find out distance between two nodes in a binary tree in Python
- Program to Find the Shortest Distance Between Two Points in C++
- Program to find maximum value of k for which we can maintain safe distance in Python
- How to get the maximum number of occupied rows and columns in a worksheet in Selenium with python?
- Program to find the minimum edit distance between two strings in C++
- Program to find maximum value by inserting operators in between numbers in Python
- Distance between Vertices and Eccentricity
- Program to find maximum element after decreasing and rearranging in Python
- Calculate distance and duration between two places using google distance matrix API in Python?

Advertisements