Two Pointer: main idea- loop through each seat and check if there is a person. record previous occupied seat index after move to next position. find the max distance between current seat with pp and previous seat with people. (cur - prev ) // 2 will be idea seat. keep this procedure and update the current best result to res.
there are two special cases need to consider where seat at either two ends is empty. so we discuss if beginning prev is None and if seat[-1] == 0 cases, where we compare res and i - prev instead of (i-prev)//2.
class Solution:
# time O(N) space O(1)
def maxDistToClosest(self, seats: List[int]) -> int:
# step1: initialize res and prev
res = float('-inf')
prev = None
# step2: loop through seats
for i in range(len(seats)):
# step3 check if current seat is occupied
if seats[i] == 1:
# step3.1: check if prev seat is recorded(if begining position be a good candidate to sit )
if prev == None:
res = i
# step3.2 if prev has record, compare res and (i-prev)//2 and update best pos to res
else:
res = max(res,(i-prev)//2)
# step 3.3: update prev with current seat before entering next seat
prev = i
# step4 after loop end: check if last seat occupied, if not, compare best res for far with potential sit at end distance
if seats[-1] != 1:
res = max(res,len(seats)-1-prev)
# step5
return res