Skip to content

Commit 7d0ae11

Browse files
committed
add 849 Maximize Distance to Closest Person
1 parent f1ea1f7 commit 7d0ae11

File tree

1 file changed

+36
-0
lines changed
  • arrays/849_Maximize_Distance_to_Closest_Person

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def max_dist_to_closest(seats: list[int]) -> int:
2+
"""
3+
Calculate the maximum distance to the closest occupied seat in a row.
4+
5+
The function finds the maximum possible distance a person can have to the nearest
6+
occupied seat when choosing a seat in a row represented by a binary list,
7+
where 1 represents an occupied seat and 0 represents an empty seat.
8+
9+
:param seats: A list of integers where 0 represents an empty seat and 1 represents
10+
an occupied seat. The list must contain at least one occupied seat.
11+
:return: The maximum distance to the closest occupied seat. The distance is measured
12+
as the number of seats between two positions (inclusive of endpoints).
13+
"""
14+
length = len(seats)
15+
left = None
16+
right = None
17+
result = 1
18+
19+
for index in range(length):
20+
if seats[index] == 0:
21+
if left is None:
22+
left = index
23+
right = index
24+
if (left == 0) or (right == length - 1):
25+
result = max(result, right - left + 1)
26+
else:
27+
result = max(result, (right - left + 2) // 2)
28+
else:
29+
left = None
30+
right = None
31+
return result
32+
33+
34+
assert max_dist_to_closest(seats=[1, 0, 0, 0, 1, 0, 1]) == 2, 'Test 1 Failed'
35+
assert max_dist_to_closest(seats=[1, 0, 0, 0]) == 3, 'Test 2 Failed'
36+
assert max_dist_to_closest(seats=[0, 1]) == 1, 'Test 3 Failed'

0 commit comments

Comments
 (0)