605. Can Place Flowers

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 if n new flowers can be planted in the flowerbed

 Examples:

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

Note: Didn't handle n = 0 case. Made a mistake in i ==L-1 case, wrote i < L-1

def canPlaceFlowers(flowerbed: List[int], n: int):
       
    i = 0
    placed = 0
    L = len(flowerbed)
   
    while i < L and placed < n:
        if  (not i or not flowerbed[i-1]) \
            and \
            not flowerbed[i] \
            and \
            (i == L-1 or not flowerbed[i+1]):
           
            flowerbed[i] = 1
            placed += 1                            
        i += 1
       
    return placed >= n

Comments

Popular posts from this blog

347. Top K Frequent Elements

849. Maximize Distance to Closest Person

674. Longest Continuous Increasing Subsequence