Saturday, December 10, 2022

[LeetCode] Can Place Flowers

Problem: 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:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false


Approach: It's a simple problem to solve. You can understand the approach by just looking at the implementation.


Implementation in C#:

    public bool CanPlaceFlowers(int[] flowerbed, int n)
    {
        int length = flowerbed?.Length ?? 0;
        if (length == 0)
        {
            return n == 0;
        }
        if (length == 1)
        {
            if (flowerbed[0] == 1)
            {
                return n == 0;
            }
            if (flowerbed[0] == 0)
            {
                return n <= 1;
            }
        }
        int maxFlowersPlaced = 0;
        for (int i = 0; i < flowerbed.Length; ++i)
        {
            if (flowerbed[i] != 1)
            {
                if (i == 0)
                {
                    if (flowerbed[i + 1] == 0)
                    {
                        ++maxFlowersPlaced;
                        flowerbed[i] = 1;
                    }
                }
                else if (i == flowerbed.Length - 1)
                {
                    if (flowerbed[i - 1] == 0)
                    {
                        ++maxFlowersPlaced;
                        flowerbed[i] = 1;
                    }
                }
                else if (flowerbed[i - 1] == 0 && flowerbed[i + 1] == 0)
                {
                    ++maxFlowersPlaced;
                    flowerbed[i] = 1;
                }
            }
        }
        return maxFlowersPlaced >= n;
    }

Complexity: O(n)

No comments:

Post a Comment