A somewhat different solution (Java) - counting empty spots


  • 0
    I

    It seems to work...

    public class Solution {
        public boolean canPlaceFlowers(int[] flowerbed, int n) {
            int p = 1;
            for (int i: flowerbed) {
                if (i == 1) p = 0; // reset p when it's not empty
                else p ++;
                if (p == 3) { // 1 extra plant for 3 empty spots to begin with
                    p = 1; // 1 extra plant for every 2 more empty spots
                    n --;
                }
                if (n == 0) return true;
            }
            if (p == 2 && n == 1) return true; // only need 2 empty spots for 1 extra plant at the end of the flowerbed. same applies to the beginning
            return false;
        }
    }
    

Log in to reply
 

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