Java one pass verbose solution


  • 0
    U
    public class Solution {
        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            
            if (n == 0) {
                return true;
            }
            if (flowerbed.length == 1 && flowerbed[0] == 0 && n == 1) {
                return true;
            }
            
            for (int i = 0, count = 0; i < flowerbed.length; i++) {
                if (flowerbed[i] == 1) {
                    count = 0;
                } else {
                    count++;
                    if (i == 0 && (flowerbed.length > 1 && flowerbed[1] == 0) || (count == 2 && (i == flowerbed.length - 1 || flowerbed[i+1] != 1))) {
                        count = 0;
                        n--;
                        if (n <= 0) {
                            return true;
                        }
                    }
                }
            }
            
            return false;
        }
    }
    
    

Log in to reply
 

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