Skip to content

849. Maximize Distance to Closest Person 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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)