Sponsored
Sponsored
This approach involves a single pass through the flowerbed array, considering each plot one by one. For each zero found, we check whether it's possible to plant a flower by ensuring that both neighboring plots (if they exist) are not planted. If it's possible, we plant the flower (i.e., change the zero to one) and reduce the count of n. The process stops early if n becomes zero. This greedy method ensures efficiency by trying to plant a flower at each opportunity.
Time Complexity: O(m), where m is the length of the flowerbed array.
Space Complexity: O(1), as no extra space is used except for variables.
1#include <stdbool.h>
2
3bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n) {
4 for (int i = 0; i < flowerbedSize; i++) {
5 if (flowerbed[i] == 0) {
6 bool isPrevEmpty = (i == 0) || (flowerbed[i - 1] == 0);
7 bool isNextEmpty = (i == flowerbedSize - 1) || (flowerbed[i + 1] == 0);
8 if (isPrevEmpty && isNextEmpty) {
9 flowerbed[i] = 1;
10 n--;
11 if (n == 0) return true;
12 }
13 }
14 }
15 return n <= 0;
16}
This C solution iterates through the flowerbed, checking the conditions for planting flowers by ensuring adjacent plots are empty. It directly modifies the flowerbed array in the process, which simulates planting the flowers. If the required number of flowers (n) is planted, it returns early.
This approach calculates the maximum number of flowers that can be planted by counting the stretches of zeros between planted flowers or array boundaries. For each encounter of a continuous stretch of zeros, determine how many flowers can be planted and accumulate this count until it reaches or exceeds n, or if it proves impossible.
Time Complexity: O(m), where m is the length of the flowerbed.
Space Complexity: O(1), only a constant amount of extra space is required.
1
The Python solution simplifies flower planting by viewing the entire process as counting potential spaces between rows of zeros, considering virtual zeros at the start and end. It calculates the necessary planting spots neatly without explicit in-place alteration.