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 where the viewer sits 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] [1, 0, 0, 0] place = ((right - left) / 2) """ func maxPlaces(arr []int) int { }
sobes.tech AI
Answer from AI
You need to find the position (index) with the maximum minimal distance to the nearest occupied seat (1). To do this, we will iterate through the array, find the gaps between occupied seats, and calculate the maximum distance.
Algorithm:
- Iterate through the row, remembering the indices of occupied seats.
- Consider three cases:
- Free seats at the beginning of the row before the first occupied seat.
- Free seats between two occupied seats.
- Free seats at the end of the row after the last occupied seat.
- For gaps between occupied seats, the distance will be half the length of the gap (rounded down).
- For the ends — the distance is equal to the length of the free segment.
- Return the maximum found distance.
Example implementation in Go:
func maxPlaces(arr []int) int {
n := len(arr)
maxDist := 0
prev := -1
for i := 0; i < n; i++ {
if arr[i] == 1 {
if prev == -1 {
// Free seats at the beginning
maxDist = i
} else {
// Free seats between prev and i
dist := (i - prev) / 2
if dist > maxDist {
maxDist = dist
}
}
prev = i
}
}
// Free seats at the end
if n-1-prev > maxDist {
maxDist = n - 1 - prev
}
return maxDist
}
This code returns the maximum distance to the nearest viewer where a new viewer will sit.