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
This Java solution provides a direct count of available planting spaces by iterating through each plot and using additional zeros at boundaries to simplify counting logic. The result checks if planting n flowers is feasible within the calculated potential spaces.