LeetCode 849: Maximize Distance to Closest Person
Problem Description
Explanation:
- We can solve this problem by iterating through the array and finding the maximum distance between consecutive occupied seats or the start/end of the array and an occupied seat.
- We calculate the distance by keeping track of the last index of an occupied seat and updating the maximum distance whenever we find a new occupied seat.
- We handle the edge cases of the first and last seat separately to calculate the distance to the closest person from the start and end respectively.
- Finally, we return the maximum distance calculated.
Time complexity: O(n) where n is the number of seats
Space complexity: O(1)
Solutions
class Solution {
public int maxDistToClosest(int[] seats) {
int maxDistance = 0;
int lastOccupied = -1;
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 1) {
if (lastOccupied == -1) {
maxDistance = i;
} else {
maxDistance = Math.max(maxDistance, (i - lastOccupied) / 2);
}
lastOccupied = i;
}
}
return Math.max(maxDistance, seats.length - 1 - lastOccupied);
}
}
Related LeetCode Problems
Loading editor...