A straightforward solution with counting


  • 0
    J

    class Solution {
    public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {

        int size = flowerbed.size();
        int sum = 0;
        int start = -1;     
    
        for (int i = 0; i < size; ++i)
        {
            if (flowerbed[i] == 1)
            {
                if (i - start > 2)
                    sum += ceil((i - start - 2) / 2.0);
    
                start = i + 1;
            }
        }
        
        if (start < size)
            sum += ceil((size - start - 1) / 2.0);
        
        return sum >= n;
    }
    

    };


Log in to reply
 

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