Intern
""" Seats in the cinema are arranged in a single row. A newly arrived viewer chooses a seat, to sit as far away as possible from other viewers in the row. That is, the distance from the seat to the nearest 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 distance (number of gaps between seats) from the chosen seat to the nearest viewer. [1, 0, 0, 0, 1] -> 2 [1, 0, 1, 0, 0, 1, 0, 0, 1] -> 2 [1, 0, 1, 0] -> 1 [0, 0, 0, 1] -> 3 [1, 0, 0, 0] -> 3 place = ((right - left) / 2) """ func maxPlaces(arr []int) int { }
sobes.tech AI
Answer from AI
To find the maximum distance to the nearest spectator, consider three situations:
- Empty seats at the beginning of the row before the first occupied seat.
- Empty seats at the end of the row after the last occupied seat.
- Empty seats between two occupied seats — in this case, choose the middle of the gap.
Algorithm:
- Traverse the row to find the indices of occupied seats.
- Calculate the distances at the beginning and end of the row.
- For each gap between occupied seats, compute half the length of the gap (rounding down).
- The maximum of these values will be the answer.
Example implementation in Go:
func maxPlaces(arr []int) int {
n := len(arr)
left := -1
maxDist := 0
// Find the first occupied seat
for i, seat := range arr {
if seat == 1 {
left = i
maxDist = left // distance from the start of the row
break
}
}
// Traverse the row to find the maximum distance between occupied seats
for i := left + 1; i < n; i++ {
if arr[i] == 1 {
dist := (i - left) / 2
if dist > maxDist {
maxDist = dist
}
left = i
}
}
// Check the distance from the last occupied seat to the end of the row
if n-1-left > maxDist {
maxDist = n - 1 - left
}
return maxDist
}
This code returns the maximum distance to the nearest spectator where a new spectator can sit.