Leetcode 605. Can Place Flowers

Problem

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.

Algorithm

Greedy. Place the flower in the leftmost available position each time, maximizing the number of flowers that can be placed.

Code

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        bed_size = len(flowerbed)
        for i in range(bed_size):
            if (i == 0 or not flowerbed[i-1]) and (i == bed_size-1 or not flowerbed[i+1]) and not flowerbed[i]:
                flowerbed[i] = 1
                n -= 1
                if n <= 0:
                    return True
        return n <= 0

相关推荐

  1. LEETCODE605.种花问题

    2024-04-23 17:26:02       54 阅读
  2. leetcode605-Can Place Flowers

    2024-04-23 17:26:02       29 阅读
  3. Leetcode 605. Can Place Flowers

    2024-04-23 17:26:02       35 阅读
  4. LeetCode607. 销售员

    2024-04-23 17:26:02       62 阅读
  5. LeetCode //C - 605. Can Place Flowers

    2024-04-23 17:26:02       60 阅读
  6. Leetcode 665. 非递减数列

    2024-04-23 17:26:02       48 阅读
  7. LeetCode 665. 非递减数列

    2024-04-23 17:26:02       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 17:26:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 17:26:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 17:26:02       87 阅读
  4. Python语言-面向对象

    2024-04-23 17:26:02       96 阅读

热门阅读

  1. php常见图片处理方法

    2024-04-23 17:26:02       37 阅读
  2. SpringBoot学习路线推荐

    2024-04-23 17:26:02       39 阅读
  3. 算法刷题记录 Day51

    2024-04-23 17:26:02       33 阅读
  4. 在线办公:巨头通往新质生产力的一把利剑

    2024-04-23 17:26:02       34 阅读
  5. Python-07-循环遍历、嵌套循环

    2024-04-23 17:26:02       28 阅读
  6. 支持三十多个算法的免费科学计算API

    2024-04-23 17:26:02       32 阅读
  7. 代码托管(二)git(1)介绍

    2024-04-23 17:26:02       37 阅读
  8. next server 组件 加载client 组件,使用suspense

    2024-04-23 17:26:02       32 阅读
  9. 更全面的Embedding介绍

    2024-04-23 17:26:02       39 阅读