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-based index).
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.
0
.1
(where a person is sitting).0
).Step-by-step approach:
1
is found, update the distance for the zeroes between the previous one and the current one.1
and trailing zeroes after the last 1
.#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int maxDistToClosest(vector<int>& seats) {
int n = seats.size();
int last_person = -1;
int max_dist = 0;
for (int i = 0; i < n; ++i) {
if (seats[i] == 1) {
if (last_person != -1) {
// Case where we're between two people.
int dist = (i - last_person) / 2;
max_dist = max(max_dist, dist);
} else {
// Case where we have leading zeroes.
max_dist = i;
}
last_person = i;
}
}
// Case where we have trailing zeroes.
if (last_person != -1) {
max_dist = max(max_dist, n - last_person - 1);
}
return max_dist;
}
O(n)
, where n
is the number of seats. This is because we go through the array only once.O(1)
, as we are using only a constant amount of extra space.In summary, this solution efficiently computes the maximum distance to the closest person by considering both the cases of leading and trailing zeroes with respect to seated people, ensuring that Alex can find the optimal seat.
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?