6-liner C++ O(N) greedy solution


  • 0

    Greedy Algorithm: Just count the length of gap (consecutive 0's) and a "plantable" spot will be every other position in a gap.

    NOTE: imagine to pad left and right ends with an extra 0 because each end has only one neighbor.

        bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            flowerbed.push_back(0);
            int gap = 1;
            for (int x : flowerbed) {
                bool plantable = x? (gap=0) : (++gap > 2 && gap%2);
                if ((n-=plantable) <= 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.