Simple iterative solution


  • 0
    L

    The problem looks trivial but I ran into quite a few edge cases.

    public boolean canPlaceFlowers(int[] flowerbed, int n) {
            int i=0;
            while(i<flowerbed.length) {
                int prev = i==0?0:flowerbed[i-1];
                int curr = flowerbed[i];
                int next = 0;
                if(i<flowerbed.length-1) {
                    next = flowerbed[i+1];
                }
    
                if(prev==0 && curr==0 && next==0) {
                    n--;
                    if(n==0) {
                        return true;
                    }
                    flowerbed[i]=1;
                }
                i += 1;
            }
            return n<=0;
            
        }
    

Log in to reply
 

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