[LeetCode] Maximize Distance to Closest Person

849. Maximize Distance to Closest Person

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int res = 0, l = 0, r = seats.size() - 1;
while(!seats[l]) l++;
while(!seats[r]) r--;

res = max(l, (int)seats.size() - r - 1);
while(l < r) {
int nl = l + 1;
while(!seats[nl]) nl++;
res = max(res, (nl - l)/2);
l = nl;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/19/PS/LeetCode/maximize-distance-to-closest-person/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.