Skip to content

849. Maximize Distance to Closest Person

https://leetcode.com/problems/maximize-distance-to-closest-person/

js
/**
 * @param {number[]} seats
 * @return {number}
 */
var maxDistToClosest = function(seats) {
  const n = seats.length
  let l = 0
  let r = n - 1

  while (seats[l] == 0) {
    l++
  }
  while (seats[r] == 0) {
    r--
  }

  let count = 0
  let maxlen = 0

  for (let i of seats.slice(l, r)) {
    if (i == 1) {
      count = 0
    } else {
      count++
      maxlen = Math.max(count, maxlen)
    }
  }

  return Math.max((maxlen + 1) / 2 >> 0, l, n - r - 1)
}
py
class Solution:

    def maxDistToClosest(self, seats):
        """
        :type seats: List[int]
        :rtype: int
        """
        n = len(seats)
        l = 0
        r = n - 1

        while seats[l] == 0:
            l += 1
        while seats[r] == 0:
            r -= 1

        count = 0
        maxlen = 0

        for i in seats[l:r]:
            if i == 1:
                count = 0
            else:
                count += 1
                maxlen = max(count, maxlen)

        return max((maxlen + 1) // 2, l, n - r - 1)