You are given an array representing a row of seats where seats[i] = 1
represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.

Input: seats =[1,0,0,0,1,0,1]Output: 2Explanation:
If Alex sits in the second open seat(i.e. seats[2]), then the closest person has distance 2.If Alex sits in any other open seat, the closest person has distance 1.Thus, the maximum distance to the closest person is2.
Input: seats =[1,0,0,0]Output: 3Explanation:
If Alex sits in the last seat(i.e. seats[3]), the closest person is3 seats away.This is the maximum distance possible, so the answer is3.
The largest distance to the closest person is determined by the largest block of empty seats between two people, or the empty seats at the start or end of the row. For each empty seat, the closest person is either to the left or right, so we want to maximize the minimum distance to a person.
classSolution {
public:int maxDistToClosest(vector<int>& seats) {
int n = seats.size(), ans =0, last =-1;
for (int i =0; i < n; ++i) {
if (seats[i] ==1) {
if (last ==-1) ans = i;
else ans = max(ans, (i - last) /2);
last = i;
}
}
ans = max(ans, n -1- last);
return ans;
}
};
funcmaxDistToClosest(seats []int) int {
n, ans, last:= len(seats), 0, -1fori:=0; i < n; i++ {
ifseats[i] ==1 {
iflast==-1 {
ans = i } else {
d:= (i-last) /2ifd > ans {
ans = d }
}
last = i }
}
ifn-1-last > ans {
ans = n-1-last }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintmaxDistToClosest(int[] seats) {
int n = seats.length, ans = 0, last =-1;
for (int i = 0; i < n; i++) {
if (seats[i]== 1) {
if (last ==-1) ans = i;
else ans = Math.max(ans, (i - last) / 2);
last = i;
}
}
ans = Math.max(ans, n - 1 - last);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmaxDistToClosest(seats: IntArray): Int {
var ans = 0var last = -1for (i in seats.indices) {
if (seats[i] ==1) {
if (last == -1) ans = i
else ans = maxOf(ans, (i - last) / 2)
last = i
}
}
ans = maxOf(ans, seats.size - 1 - last)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmaxDistToClosest(self, seats: list[int]) -> int:
n = len(seats)
ans = last =-1for i, v in enumerate(seats):
if v ==1:
if last ==-1:
ans = i
else:
ans = max(ans, (i - last) //2)
last = i
ans = max(ans, n -1- last)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnmax_dist_to_closest(seats: Vec<i32>) -> i32 {
let n = seats.len();
letmut ans =0;
letmut last =-1;
for (i, &v) in seats.iter().enumerate() {
if v ==1 {
if last ==-1 {
ans = i asi32;
} else {
ans = ans.max(((i - last asusize) /2) asi32);
}
last = i asi32;
}
}
ans = ans.max((n asi32-1- last) asi32);
ans
}
}