Algorithm
Problem Name: 605. Can Place Flowers
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1 Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2 Output: false
Constraints:
1 <= flowerbed.length <= 2 * 104flowerbed[i]is0or1.- There are no two adjacent flowers in
flowerbed. 0 <= n <= flowerbed.length
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
for (int i = 0; i < flowerbed.length && n > 0; i++) {
if (flowerbed[i] == 0) {
if (i == 0 && (flowerbed.length == 1 || flowerbed[i + 1] == 0)) {
flowerbed[i] = 1;
n--;
} else if (i == flowerbed.length - 1 && flowerbed[i - 1] == 0) {
flowerbed[i] = 1;
n--;
} else if (i + 1 < flowerbed.length && flowerbed[i + 1] == 0 && i - 1 >= 0 && flowerbed[i - 1] == 0) {
flowerbed[i] = 1;
n--;
}
}
}
return n == 0;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const canPlaceFlowers = function(flowerbed, n) {
let count = 0
const clone = flowerbed
for(let i = 0; i < clone.length; i++) {
if(clone[i] === 0) {
if(i === 0 && (clone[i + 1] === 0 || clone[i+1] == null)){
count++
clone[i] = 1
}
if(i > 0 && i < clone.length - 1 && clone[i - 1] === 0 && clone[i + 1] === 0) {
count++
clone[i] = 1
}
if(i === clone.length - 1 && clone[i - 1] === 0 && clone[i] === 0> {
count++
clone[i] = 1
}
}
}
return count >= n ? true : false
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
num=n
if len(flowerbed)<=1:
if (num==1 and flowerbed==[0]) or (num==0):
return True
else:
return False
if flowerbed[0]==0 and flowerbed[1]==0:
flowerbed[0]=1
num-=1
if flowerbed[-1]==0 and flowerbed[-2]==0:
flowerbed[-1]=1
num-=1
for i in range(1,len(flowerbed)-2):
if flowerbed[i]!=1 and flowerbed[i+1]!=1 and flowerbed[i-1]!=1:
flowerbed[i]=1
num-=1
if num<=0:
return True
return False
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0605_CanPlaceFlowers
{
public bool CanPlaceFlowers(int[] flowerbed, int n)
{
var 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;
count++;
}
if (count >= n) return true;
}
return count >= n;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output