LeetCode Solutions
849. Maximize Distance to Closest Person
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
const int n = seats.size();
int ans = 0;
int j = -1;
for (int i = 0; i < n; ++i)
if (seats[i] == 1) {
ans = j == -1 ? i : max(ans, (i - j) / 2);
j = i;
}
return max(ans, n - j - 1);
}
};
class Solution {
public int maxDistToClosest(int[] seats) {
final int n = seats.length;
int ans = 0;
int j = -1;
for (int i = 0; i < n; ++i)
if (seats[i] == 1) {
ans = j == -1 ? i : Math.max(ans, (i - j) / 2);
j = i;
}
return Math.max(ans, n - j - 1);
}
}
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
n = len(seats)
ans = 0
j = -1
for i in range(n):
if seats[i] == 1:
ans = i if j == -1 else max(ans, (i - j) // 2)
j = i
return max(ans, n - j - 1)