How is this possible?


  • 0
    R
    class Solution {
    public:
        bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            int i = 0;
            int sz = flowerbed.size();
            while(i < sz){
                if(flowerbed[i] == 1)
                    i++;
                else{
                    if(flowerbed[i-1] == 1)
                        i++;
                    else if(flowerbed[i+1] == 1)
                        i += 3;
                    else{
                        flowerbed[i] = 1;
                        i += 2;
                        n--;
                    }
                }
            }
            return (n == 0);
        }
    };
    

    For the above code, I am getting true for
    [0,0,1,0,0]
    2,
    but on submission, I am getting false.
    Can someone explain?

    0_1512637522120_605_Leetcode.png


  • 0
    R

    @RK21
    Update :
    Sorry, forgot to check for bounds, but still I am facing the same problem.

    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
            int i = 0;
            int sz = flowerbed.size();
            while(i < sz){
                if(flowerbed[i] == 1)
                    i++;
                else{
                    if(i > 0 && flowerbed[i-1] == 1)
                        i++;
                    else if(i < sz-1 && flowerbed[i+1] == 1)
                        i += 3;
                    else{
                        flowerbed[i] = 1;
                        i += 2;
                        n--;
                    }
                }
            }
            return (n == 0);
        }
    

  • 0
    S

    Sahi baat hai


  • 0
    R

    Got it, need to check the value of n in while loop, to see if it doesn't go beyond zero.


  • 0
    R

    not beyond, below zero


Log in to reply
 

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