The Can Place Flowers problem involves determining whether it is possible to plant a given number of flowers in a flowerbed without violating the rule that no two flowers can be adjacent.
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int count = 0;
for (int i = 0; i < flowerbed.length; i++) {
if (flowerbed[i] == 0 &&
(i == 0 || flowerbed[i - 1] == 0) &&
(i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1; // Plant a flower
count++;
}
if (count >= n) {
return true; // Enough flowers planted
}
}
return count >= n; // Check if we could plant enough flowers
}
}
O(N)
, where N
is the length of the flowerbed array.O(1)
, as we modify the flowerbed array in place.Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Explanation:
- Plant a flower at index 2. The flowerbed becomes [1,0,1,0,1].
- It is possible to plant 1 flower.