Problem · Array
Maximize Distance to Closest Person — Return the Seat
Learn this problemProblem statement
You are given an array seats, where seats[i] = 1 means seat i is occupied and seats[i] = 0 means it is empty. At least one seat is empty and at least one seat is occupied.
Choose an empty seat that maximizes its distance to the closest occupied seat, and return the index of that seat. If several seats have the same maximum distance, return the smallest index.
Function
bestSeat(seats: int[]) → intExamples
Example 1
seats = [1, 0, 0, 0, 1, 0, 1]return = 2Seat 2 is two positions from the closest occupied seat, which is optimal.
Example 2
seats = [1, 0, 0, 0]return = 3The final seat is three positions from the only occupied seat.
Example 3
seats = [0, 1]return = 0Seat 0 is the only empty seat.
Example 4
seats = [1, 0, 0, 1, 0, 0, 1]return = 1Seats 1, 2, 4, and 5 all have closest-person distance 1; the smallest index is 1.
Constraints
2 <= seats.length <= 20000seats[i]is0or1.- At least one seat is empty.
- At least one seat is occupied.
- On a tie, return the smallest seat index.