Can Place Flowers
Problem statement
A flowerbed is a row of plots. You are given an integer array flowerbed, where flowerbed[i] = 1 means plot i already has a flower and flowerbed[i] = 0 means it is empty. You are also given an integer n.
Flowers cannot grow in adjacent plots. A new flower can go only in an empty plot whose left and right neighbors are both empty. The first and last plots have only one neighbor; the side outside the row counts as empty.
Return true if you can plant n new flowers without breaking this rule, and false otherwise. Flowers that are already planted cannot be moved.
Function
canPlaceFlowers(flowerbed: int[], n: int) → booleanExamples
Example 1
flowerbed = [1,0,0,0,0,1]n = 1return = truePlot 1 cannot be used because plot 0 has a flower, and plot 4 cannot be used because plot 5 has a flower. Plots 2 and 3 both have empty neighbors, so one flower fits in either of them.
One new flower is enough, so the answer is true.
Example 2
flowerbed = [1,0,0,0,0,1]n = 2return = falseThis is the same flowerbed. Only plots 2 and 3 can take a flower, and they are next to each other, so planting in one blocks the other. At most one new flower fits.
Two are needed, so the answer is false.
Example 3
flowerbed = [0,0,1,0,0]n = 2return = truePlot 0 is at the edge: its only neighbor, plot 1, is empty, so it can take a flower. Plot 4 is at the other edge with an empty neighbor, plot 3, so it can take one too. Plots 1 and 3 are next to the flower in plot 2.
Planting in plots 0 and 4 gives two new flowers, so the answer is true.
Constraints
1 <= flowerbed.length <= 2 * 10^4flowerbed[i]is0or1.- No two adjacent plots in
flowerbedboth have a flower. 0 <= n <= flowerbed.length