Maximize Distance to Closest Person LeetCode solution in Python

1
class Solution:
2
def maxDistToClosest(self, seats: List[int]) -> int:
3
# strategy is greedy solution:
4
# calculate local maximum for each interval: (b-a)//2
5
# then take max of local maximums
6
# the solution is O(n)
7
# I find this solution clear, but uses 5 passes
8

9
# get all the occupied seat nums
10
seat_nums = [ix for ix, val in enumerate(seats) if val == 1]
11

12
# check the ends
13
left_max, right_max = min(seat_nums), len(seats) - max(seat_nums) - 1
14

15
# calculate max distance for each gap
16
dists = [(y - x) // 2 for x, y in zip(seat_nums, seat_nums[1:])]
17

18
# take max of sitting on either end + each gap
19
return max([left_max, right_max, *dists])

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0