Sobes.tech
Intern

""" Seats in a cinema are arranged in a row. A newly arrived viewer chooses a seat to sit as far as possible from other viewers. 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 the 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, 1] -> 2 [1, 0, 1, 0] -> 1 """

sobes.tech AI

Answer from AI

go package main

import ( "fmt" "math" )

func maxDistance(seats []int) int { maxDist := 0 lastOccupied := -1

for i, seat := range seats {
	if seat == 1 {
		if lastOccupied == -1 {
			// distance from the start of the row to the first occupied seat
			maxDist = i
		} else {
			// distance between two occupied seats
			midDist := (i - lastOccupied) / 2
			if midDist > maxDist {
				maxDist = midDist
			}
		}
		lastOccupied = i
	}
}
// distance from the last occupied seat to the end of the row
tailDist := len(seats) - 1 - lastOccupied
if tailDist > maxDist {
	maxDist = tailDist
}
return maxDist

}

func main() { fmt.Println(maxDistance([]int{1, 0, 0, 0, 1})) // 2 fmt.Println(maxDistance([]int{1, 0, 1, 0, 0, 1, 0, 0, 1})) // 2 fmt.Println(maxDistance([]int{1, 0, 1, 0})) // 1 }


Explanation:
- Iterate through the row, remembering the index of the last occupied seat.
- For each occupied seat, calculate the distance to the previous one and take half of it (the furthest seat between them).
- Also consider the distances from the start of the row to the first occupied seat and from the last occupied seat to the end of the row.
- Return the maximum of these distances.