Leetcode 849. Maximize Distance to Closest Person
You are given an array representing a row of seats where seats[i]
= 1 represents a person sitting in the i-th
seat, and seats[i]
= 0 represents that the i-th
seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance to the closest person is maximized. Return that maximum distance to the closest person.
seats
be empty?
We can solve this problem in a single pass through the array. The strategy involves:
maxDist
.lastOccupied
.seats[i] == 1
), update the distance for each segment.Finally, we need to handle the cases where the person can sit at the beginning of the row or at the end.
Let’s implement this strategy in Java:
public class Solution {
public int maxDistToClosest(int[] seats) {
int n = seats.length;
int maxDist = 0;
int lastOccupied = -1;
for (int i = 0; i < n; i++) {
if (seats[i] == 1) {
if (lastOccupied == -1) {
// Distance from the start of the row to this person
maxDist = i;
} else {
// Distance between two people
maxDist = Math.max(maxDist, (i - lastOccupied) / 2);
}
lastOccupied = i;
}
}
// Distance from the last person to the end of the row
if (seats[n - 1] == 0) {
maxDist = Math.max(maxDist, n - 1 - lastOccupied);
}
return maxDist;
}
}
The time complexity of this solution is O(n), where n
is the length of the input array seats
. This is because we make a single pass through the array to calculate the maximum distance.
By following this approach, we efficiently determine the maximum distance Alex can sit from the closest person in linear time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?