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.
1class Solution {
2 public boolean canPlaceFlowers(int[] flowerbed, int n) {
3 for (int i = 0; i < flowerbed.length; i++) {
4 if (flowerbed[i] == 0) {
5 boolean isPrevEmpty = (i == 0) || (flowerbed[i - 1] == 0);
6 boolean isNextEmpty = (i == flowerbed.length - 1) || (flowerbed[i + 1] == 0);
7 if (isPrevEmpty && isNextEmpty) {
8 flowerbed[i] = 1;
9 n--;
10 if (n == 0) return true;
11 }
12 }
13 }
14 return n <= 0;
15 }
16}
This Java solution iterates over the flowerbed using similar conditions to the C/C++ implementations. It utilizes Java's array boundaries to manage checking adjacent plots safely, altering the in-place state of the array to simulate flower planting.
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 public bool CanPlaceFlowers(int[] flowerbed, int n) {
int count = 0, consecutiveZeros = 1;
foreach (int plot in flowerbed) {
if (plot == 0) {
consecutiveZeros++;
} else {
count += (consecutiveZeros - 1) / 2;
consecutiveZeros = 0;
}
}
count += consecutiveZeros / 2;
return count >= n;
}
}
This C# solution uses a consistent counting technique, factoring in imaginary zeros at the edges. With this pattern, it simplifies the process by accounting for usable spaces between sequences of zeros.