Maximize Distance to Closest Person LeetCode solution in Java

1
class Solution {
2
public int maxDistToClosest(int[] seats) {
3
int size = seats.length;
4
int max = 0;
5
int start = -1;
6
int end = -1;
7

8
for (int i = 0; i < size; i++) {
9
if (seats[i] != 0) {
10
start = end; // update start to end when we have a filled seat.
11
end = i; // update end with i pointer when we have a filled seat.
12
if (start == -1) max = i; // for special case when there is only '1' in the array
13
else max = Math.max((end - start) / 2, max); // updating max.
14
}
15
}
16

17
// Handeling speical cases before returning max.
18
// 1) last element is 0 as we wont be updating max for that in above loop.
19
// 2) when there only single '1' in the array, we need to make sure whether right half is bigger
20
// than the left half.
21

22
if (seats[size - 1] == 0 || start == -1) return Math.max(max, (size - 1 - end));
23
return max;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0