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 <vector>
2using namespace std;
3
4class Solution {
5public:
6 bool canPlaceFlowers(vector<int>& flowerbed, int n) {
7 for (int i = 0; i < flowerbed.size(); i++) {
8 if (flowerbed[i] == 0) {
9 bool isPrevEmpty = (i == 0) || (flowerbed[i - 1] == 0);
10 bool isNextEmpty = (i == flowerbed.size() - 1) || (flowerbed[i + 1] == 0);
11 if (isPrevEmpty && isNextEmpty) {
12 flowerbed[i] = 1;
13 n--;
14 if (n == 0) return true;
15 }
16 }
17 }
18 return n <= 0;
19 }
20};
The C++ solution uses a similar approach to the C solution with the additional advantage of using the std::vector dynamic array. It implements boundary checks efficiently to ensure no adjacent flowers are planted.
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.