605. Can Place Flowers

 

Promble

link: https://leetcode.com/problems/can-place-flowers/description/

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.

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false

Approach

Thought

  1. def count:int to store the empty plot.
  2. if n == 0, dont input the flower, return True.
  3. loop i in range(len(flowerbed)).
    1. check flowerbed[i] is empty.
      1. check left and right is empty.
      2. when left, right is empty:
        1. flowerbed[i] = 1 # input the flow.
        2. count += 1.
        3. check count >= n: return True.
  4. if not, return False.

Code

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        count = 0

        if n == 0:
            return True

        for i in range(len(flowerbed)):
            if flowerbed[i] == 0:
                # check left and right
                left = (i==0) or (flowerbed[i-1] == 0)
                right = (i==len(flowerbed)-1) or (flowerbed[i+1]==0)

                if left and right:
                    flowerbed[i] = 1
                    count += 1 
                    if count >= n:
                        return True 

        return False