Intern
""" Seats in a cinema are arranged in a single row. A newly arrived viewer chooses a seat to sit as far as possible from others. That is, the distance from the seat they choose to the nearest viewer should be maximized. It is guaranteed that there are always free seats 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 distance (number of gaps between chairs) from the chosen seat to the nearest viewer. [1, 0, 0, 0, 1] -> 2 [1, 0, 1, 0, 0, 1, 0, 0, 0, 1] -> 2 [1, 0, 1, 0] -> 1 """ func maxPlaces(arr []int) int { }
sobes.tech AI
Answer from AI
To solve the problem, you need to find a free seat (0) that has the maximum minimal distance to the nearest occupied seat (1).
Algorithm:
- Iterate through the array and record the indices of occupied seats.
- For each free seat, calculate the distance to the nearest occupied seat.
- Return the maximum of these distances.
Example implementation in Go:
func maxPlaces(arr []int) int {
occupied := []int{}
for i, v := range arr {
if v == 1 {
occupied = append(occupied, i)
}
}
maxDist := 0
for i, v := range arr {
if v == 0 {
// Find the minimum distance to any occupied seat
minDist := len(arr)
for _, occ := range occupied {
d := i - occ
if d < 0 {
d = -d
}
if d < minDist {
minDist = d
}
}
if minDist > maxDist {
maxDist = minDist
}
}
}
return maxDist
}
Examples:
fmt.Println(maxPlaces([]int{1, 0, 0, 0, 1})) // 2
fmt.Println(maxPlaces([]int{1, 0, 1, 0, 0, 1, 0, 0, 0, 1})) // 2
fmt.Println(maxPlaces([]int{1, 0, 1, 0})) // 1