Suppose there is a very long flower bed, and one part of the plot is planted with flowers, but the other part is not. However, flowers cannot be planted on adjacent plots. They will compete for water and both will die.
Give you an integer array flowerbed that represents the flowerbed, which is composed of a number of 0 and 1, where 0 means no flowers are planted, and 1 means flowers are planted. There is also a number n. Can n flowers be planted without breaking the planting rules? It returns true if it can, and false if it can't.
Example1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Excxample2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Idea:
First, the overall idea is to calculate the maximum amount of
flowers
to be planted as ans and compare the amount of flowers to be planted n. If ans is greater than or equal to n, n flowers can be planted, return True,
if ans is less than n, n flowers cannot be planted, return False
Group discussion afterwards
1. For the two flower beds on both sides (the flower beds with index 0, -1):
as long as the flower beds beside the two flower beds
on both sides are the flower beds on both sides of 0 , you can plant flowers
2. For the flowerbeds in the middle (except for the flowerbeds with indexes of 0, -1, 1, -2):
only when the surrounding two flowerbeds are both 0, the
middle flowerbed can plant flowers
(because the traversed flowerbed has already been planted, the next flowerbed Can’t plant flowers, just skip the next flowerbed)
3. For the two flower beds with indexes of 1 and -2,
if the surroundings of the two flower beds are 0, the flowers are planted on both sides or the results of the two flower beds are the same.
For example
If the starting sequence is
0, 0, 0, 1, then the words will be planted at index 0, or at index 1, only one can be planted
Code:
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
ans = 0
if len(flowerbed) == 1:
if flowerbed[0] == 0 and n <= 1:
return True
elif n == 0:
return True
else:
return False
if flowerbed[0] == 0 and flowerbed[1] == 0:
ans += 1
flowerbed[0] = 1
if flowerbed[-2] == 0 and flowerbed[-1] == 0:
ans += 1
flowerbed[-1] = 1
i = 2
while i < len(flowerbed) - 2:
if flowerbed[i - 1] == 0 and flowerbed[i + 1] == 0 and flowerbed[i] != 1:
flowerbed[i] = 1
ans += 1
i += 1
i += 1
if ans >= n:
return True
else:
return False
running result: