Thursday, December 6, 2018

849. Maximize Distance to Closest Person

Version #1 Naive Two Pointers 1 Pass
Time O(N)

15.28 %
class Solution {
    public int maxDistToClosest(int[] seats) {
int left = -1;
int max = 0;
for (int right = 0; right < seats.length; right++) {
if (seats[right] == 1) {
// the seat of last person
// 1[0, 0, 1, 0]
if (left == -1) {
max = Math.max(max, right);
} else {
// [1,0,0,1]
// [1,0,0,0,1]
max = Math.max(max, (right - left) / 2);
}
left = right;
}
}
// left is the last 1 [1, 0, 0]1
max = Math.max(max, seats.length - 1 - left);
return max;
}
}

No comments:

Post a Comment