Created
June 1, 2023 20:21
-
-
Save cfrank/5ef0f58884b827c030b3643babfa9f65 to your computer and use it in GitHub Desktop.
605. Can Place Flowers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function canPlaceFlowers(flowerbed: number[], n: number): boolean { | |
let openPlots = 0; | |
for (let i = 0; i < flowerbed.length; ++i) { | |
if (flowerbed[i] === 1) { | |
continue; | |
} | |
const leftSideFree = (i === 0 || flowerbed[i - 1] === 0); | |
const rightSideFree = (i + 1 >= flowerbed.length || flowerbed[i + 1] === 0); | |
if (leftSideFree && rightSideFree) { | |
flowerbed[i] = 1; | |
if ((openPlots += 1) >= n) { | |
return true; | |
} | |
} | |
} | |
// Handle cases where we never enter the for-loop | |
return openPlots >= n; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment