Sobes.tech
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 other viewers in the row. That is, the distance from the seat where the viewer will sit to the nearest It is guaranteed that there are always free seats in the row and at least Write a function that, given a row of seats (an array of zeros and ones) Example: Input: [1, 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 task is to find the position (index) in a row where a new viewer will sit the farthest from already occupied seats.

Solution idea:

  • Traverse the row to find all free seats (0).
  • For each free seat, calculate the distance to the nearest occupied seat (1).
  • Choose the seat with the maximum such distance.

Example implementation in Go:

func maxDistanceSeat(row []int) int {
    n := len(row)
    maxDist := -1
    seatIndex := -1

    for i := 0; i < n; i++ {
        if row[i] == 0 {
            // Find the distance to the nearest occupied seat
            dist := n
            for j := 0; j < n; j++ {
                if row[j] == 1 {
                    d := abs(i - j)
                    if d < dist {
                        dist = d
                    }
                }
            }
            if dist > maxDist {
                maxDist = dist
                seatIndex = i
            }
        }
    }
    return seatIndex
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

Usage example:

row := []int{1, 0, 0, 0, 1}
seat := maxDistanceSeat(row) // seat == 2

Thus, the function returns the index of the seat where the viewer will sit the farthest from others.