Maximize Distance to Closest Person - Problem
Cinema Seating Problem: You're entering a movie theater represented by an array
Your goal is to find the optimal seat that maximizes your distance from the nearest occupied seat. Think of it as finding the most "private" spot in the theater!
Example: In seats
Return: The maximum possible distance to the closest person.
seats, where seats[i] = 1 means someone is already sitting in seat i, and seats[i] = 0 means the seat is empty.Your goal is to find the optimal seat that maximizes your distance from the nearest occupied seat. Think of it as finding the most "private" spot in the theater!
Example: In seats
[1,0,0,0,1,0,1], you'd want to sit at index 2 because it's distance 2 from the nearest person (at indices 0 and 4).Return: The maximum possible distance to the closest person.
Input & Output
example_1.py โ Basic Case
$
Input:
[1,0,0,0,1,0,1]
โบ
Output:
2
๐ก Note:
Sitting at index 2 gives distance 2 to nearest people at indices 0 and 4. This is the maximum possible distance.
example_2.py โ Edge Seat
$
Input:
[1,0,0,0]
โบ
Output:
3
๐ก Note:
Sitting at the rightmost seat (index 3) gives distance 3 from the person at index 0. Edge seats can provide maximum distance.
example_3.py โ Multiple Options
$
Input:
[0,1,0,0,0,1,0]
โบ
Output:
2
๐ก Note:
The optimal seats are at indices 3 or 4, both giving distance 2 to the nearest occupied seats.
Constraints
- 2 โค seats.length โค 2 ร 104
- seats[i] is either 0 or 1
- At least one seat is empty (seats[i] = 0)
- At least one seat is occupied (seats[i] = 1)
Visualization
Tap to expand
Understanding the Visualization
1
Scan Theater Layout
Identify all occupied (1) and empty (0) seats in the row
2
Calculate Left Distances
For each seat, find distance to nearest person on the left
3
Calculate Right Distances
For each seat, find distance to nearest person on the right
4
Find Optimal Seat
Choose the empty seat with maximum distance to closest person
Key Takeaway
๐ฏ Key Insight: The optimal seat maximizes the distance to the nearest person, which occurs either at the ends of the row or in the center of the largest gap between occupied seats.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code