Suppose 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 - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
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
Note:
- The input array won't violate no-adjacent-flowers rule.
- The input array size is in the range of [1, 20000].
- n is a non-negative integer which won't exceed the input array size.
解题思路:
这道题主要是找到连续的0的数量,然后根据0的数量来判断可以放多少朵花,然后注意!起始部位连续的0和结尾连续的0的情况一定要考虑进去!!!
解题代码:
ans=0
cnt=1
for flower in flowerbed:
if flower == 0:
cnt +=1
else:
ans += abs(cnt-1)//2
cnt=0
return ans+cnt/2>=n

本文探讨了如何在遵循不相邻种花规则的前提下,在给定的花坛中种植尽可能多的花朵。通过分析花坛布局,提出了一种有效算法来确定最多能种植的花朵数量。
373

被折叠的 条评论
为什么被折叠?



