C++ Program To Find How Many Flowers Can Be Planted In A Flowerbed

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, return how many new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. 

can place flower problem, c++ example, c++ problem for practice


Program:

#include <iostream>
using namespace std;

int canPlaceFlowers(int flowerbed[], int n)    //function to find number of flowers that can be planted
{
    int count = 0;
    
    if(n == 1 && flowerbed[0] == 0)
       return 1;
    
    for(int i = 0; i < n; i++)
    {    
    	//if plot is empty then check its adjacent plots are empty or not if empty increment count
        if(flowerbed[i] == 0)
        {
            if(i == 0 && flowerbed[i+1] == 0)
            {
                count++;
                i++;
            }

            else if(i == n-1 && flowerbed[i-1] == 0)
               count++;
        
            else if(i > 0 && i < n-2 && flowerbed[i-1] == 0 && flowerbed[i+1] == 0)
            {
                count++;
                i++;
            }
        }
    }
    return count;
}

int main()
{
    int flowerbed[] = {1,0,0,0,1};
    int n = sizeof(flowerbed)/sizeof(flowerbed[0]);

    cout << "Numbers of pots that can be planted is: " << canPlaceFlowers(flowerbed,n) << endl;

    return 0;
}

Output:

Number of flowers that can be planted is: 1
To solve more problems click here.
C++ Program To Find How Many Flowers Can Be Planted In A Flowerbed C++ Program To Find How Many Flowers Can Be Planted In A Flowerbed Reviewed by Beast Coder on April 26, 2021 Rating: 5

No comments:

Powered by Blogger.