849. Maximize Distance to Closest Person

44 阅读1分钟

image.png

1.Keep record of previos of 1

class Solution {
    public int maxDistToClosest(int[] seats) {
        int res = Integer.MIN_VALUE;
        int prev = 0;
        for (int i = 0; i < seats.length; i++) {
            if (seats[i] == 1) {
                // 0000000001111
                if (seats[prev] != 1) {
                    res = Math.max(res, i - prev);
                }
                // 001000000100
                int dist = (i - prev) / 2;
                res = Math.max(res, dist);
                prev = i;
            }
        }
        // 1100000000
        res = Math.max(res, seats.length - prev - 1);

        return res;
    }
}
// keep record of previous accurance of 1
// three cases

2. Group by 0 s

class Solution {
    public int maxDistToClosest(int[] seats) {
        int res = Integer.MIN_VALUE;
        int count = 0;
        for (int i = 0; i < seats.length; i++) {
            if (seats[i] == 0) {
                count++;
            } else {
                res = Math.max(res, (count + 1) / 2);
                count = 0;
            }
        }
        
        // 00011
        for (int i = 0; i < seats.length; i++) {
            if (seats[i] == 1) {
                res = Math.max(res, i);
                break;
            }
        }

        // 11000
        for (int i = seats.length - 1; i >= 0; i--) {
            if (seats[i] == 1) {
                res = Math.max(res, seats.length - i - 1);
                break;
            }
        }
        return res;
    }
}