Skip to content

Instantly share code, notes, and snippets.

@cfrank
Created June 1, 2023 20:21
Show Gist options
  • Save cfrank/5ef0f58884b827c030b3643babfa9f65 to your computer and use it in GitHub Desktop.
Save cfrank/5ef0f58884b827c030b3643babfa9f65 to your computer and use it in GitHub Desktop.
605. Can Place Flowers
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