관리 메뉴

bright jazz music

605. Can place flowers 본문

LeetCode

605. Can place flowers

bright jazz music 2026. 1. 13. 23:23
605. Can Place Flowers
Solved
Easy
Topics
conpanies icon
Companies
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.

 

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 * 104
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length

 

풀이

function canPlaceFlowers(flowerbed: number[], n: number): boolean {
    // 인접하게 심으면 안됨
    // 양 옆에 0이여야 함. 1이 있으면 안됨
    // 순회하면서 0인 원소를 찾음. 
    // 양 옆에 1이 있는지 확인
    // 있으면 다음 원소로
    // 없으면 1로 변경
    // 순회

    for(let i = 0; i < flowerbed.length; i++) {
        if(flowerbed[i] === 0 ) {
            // if(flowerbed[i-1] !== 1 || flowerbed[i+1] !== 1) { 
            if(flowerbed[i-1] !== 1 && flowerbed[i+1] !== 1) {
                flowerbed[i] = 1;
                n--;
            }
        }


    }

    // if(n === 0) return true;

    // return false;

    /*
    greedy하게 심을 수 있는 곳은 다 심기 때문에, 필요한 것보다 더 많이 심으면 n이 음수가 됨.
    따라서 n <= 0으로 체크해야 "요구량 이상을 심었다"는 것을 올바르게 판단할 수 있음
    */

    return n <= 0;

};
Comments