Java beats 100%, count the length of consecutive zeros


  • 0

    For each segment of consecutive zeros we denote its length as len
    if both the element to the left and right of this segment are 1s we add (len-1)/2 to the total number flowers we can add
    if only one side has 1 (the head/tail of the array), then we add len/2
    if neither side has 1 (the entire array), then we add (len+1)/2

        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            int sum = 0, lo = 0, hi = 0;
            for (int i = 0; i < flowerbed.length; i++) {
                if (flowerbed[i] == 0) {
                    if (i == 0 || flowerbed[i-1] == 1) lo = i;
                    hi = i;
                } else if (i > 0 && flowerbed[i-1] == 0) {
                    sum += lo == 0 ? (hi-lo+1)/2 : (hi-lo)/2;
                }
            }
            if (flowerbed[flowerbed.length-1] == 0) sum += lo == 0 ? (hi-lo+2)/2 : (hi-lo+1)/2;
            return sum >= n;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.