You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0‘s and 1‘s, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1 Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2 Output: false
Constraints:
1 <= flowerbed.length <= 2 * 104flowerbed[i] is 0 or 1.flowerbed.0 <= n <= flowerbed.length
class Solution {
public:
bool canPlaceFlowers(vector& flowerbed, int n) {
int size= flowerbed.size();
int i=0;
if(n>size)return false;
if(size==1) return ((n==1 and flowerbed[0]==0)||(n==0));
while(i
We are here provided with a plant bed in which few of the plants are already planted and few of them are not, and we have to plant new flowers in the bed . There should be a vacant place for a flower to be planted otherwise we cannot do the same .
Also, we have to keep in mind to place flower in such a position that it should have no adjacent plants .
Here 0 represents empty plot and 1 represents a planted flower.
Let’s see the approach step by step –
The loops checks several conditions like:
By [ flowerbed( i-1)==0]
If this is true that means we can plant the flower and quantity of n number of flowers will be reduced by one.
If [ i+1==0 ] position and
[ i -1==0 ] position is vacant then the flower can be planted here .
And if the current position has already a flower planted then we simply do [ i++] .
In this way the loop works, at last it checks if ( n<=0 ) ; i.e,
If n is less than or equal to 0 , it means that all the flowers have been planted , and the function returns ‘true’ . Otherwise it returns ‘false’ .
© 2021 edSlash. All Rights Reserved.