June 23rd 2023
Problem Description permalink
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 true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Solution permalink
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
if (flowerbed.length == 1){
return (flowerbed[0] == 0) || (flowerbed[0] == 1 && n == 0)
}
var flowersThatCanBePlanted: number = 0;
var theoreticalField = [...flowerbed]
if (theoreticalField[0] == 0 && theoreticalField[1] == 0){
flowersThatCanBePlanted += 1
theoreticalField[0] = 1
}
for (var i=2; i<flowerbed.length; i++){
if (theoreticalField[i-2] == 0 && theoreticalField[i-1] == 0 && theoreticalField[i] == 0){
flowersThatCanBePlanted += 1;
theoreticalField[i - 1] = 1;
}
}
if (theoreticalField[flowerbed.length-2] == 0 && theoreticalField[flowerbed.length-1] == 0){
flowersThatCanBePlanted += 1
theoreticalField[flowerbed.length-1] = 1
}
console.log(theoreticalField, flowersThatCanBePlanted)
return flowersThatCanBePlanted >= n;
};