605. Can Place Flowers

Explanation:

  • You need to handle edge cases for the first/last slot where there aren’t any adjacent slots. The code needs two separate if statements since they need to be handled separately (don’t combine the two if statements).
  • what i did was count up the “cavity” and half of that is the actual number of flowers that can be planted in that cavity. Subtract the num by 1 for even numbers and this will work.
  • combining the “cavity” approach and handling the first and last slots, if the first or last slot is plantable, ie) 0, it is the same as incrementing the cavity by 1.
class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        def count(num):
            num = num - 1 if num % 2 == 0 else num
            return num // 2

        answer = 0
        i = 0
        while i < len(flowerbed):
            cur_len = 0
            while i < len(flowerbed) and flowerbed[i] == 0:
                if i == 0:
                    cur_len += 1
                if i == len(flowerbed) - 1:
                    cur_len += 1
                i += 1
                cur_len += 1
            if cur_len:
                answer += count(cur_len)
            i += 1
    
        return answer >= n