Middle
/* Seats in the cinema are arranged in a single row. A newly arrived viewer chooses a seat to sit as far as possible from the other viewers in the row. That is, the distance from the seat where the viewer sits to the nearest other viewer should be maximized. It is guaranteed that there are always free seats in the row and at least one viewer is already seated. Write a function that, given a row of seats (an array of zeros and ones), returns the maximum distance from the chosen seat. Input: [1, 0, 0, 0, 0, 1] Output: 2 Input: [1, 0, 1, 0, 0, 1, 0, 0, 0, 1] Output: 2 Input: [1, 0, 1, 0] Output: 1 */
sobes.tech AI
Answer from AI
The function should find the position (index with zero) where the distance to the nearest occupied seat (value 1) is maximized.
Solution idea:
- Iterate through the array, for each free seat, calculate the distance to the nearest occupied seat.
- Return the maximum such distance.
An optimal way is a single pass with counting distances to the nearest ones on the left and right.
Example in Go:
func maxDistance(seats []int) int {
n := len(seats)
leftDist := make([]int, n)
rightDist := make([]int, n)
// Fill distances to the nearest occupied seat on the left
dist := n
for i := 0; i < n; i++ {
if seats[i] == 1 {
dist = 0
} else {
dist++
}
leftDist[i] = dist
}
// Fill distances to the nearest occupied seat on the right
dist = n
for i := n - 1; i >= 0; i-- {
if seats[i] == 1 {
dist = 0
} else {
dist++
}
rightDist[i] = dist
}
maxDist := 0
for i := 0; i < n; i++ {
if seats[i] == 0 {
// Minimum distance to the nearest viewer
d := leftDist[i]
if rightDist[i] < d {
d = rightDist[i]
}
if d > maxDist {
maxDist = d
}
}
}
return maxDist
}
This function returns the maximum distance to the nearest viewer for the chosen seat.