C++ code to find tree height after n days

Suppose we have an array A with n elements. A has elements either 0 or 1. There is a tree. In consecutive n days, if A[i] is 0 it is not watered, if it is 1 then it is watered, the flower grows in the following manner −

  • If the tree is not watered for consecutive two days, it dies

  • If the tree is watered on ith day, it grows 1 cm

  • If the tree is watered on ith and (i+1)th day consecutively, it grows 5 cm instead of 1 cm.

  • If it is not watered on ith day, it will not grow.

At the beginning, the tree is 1cm long. We have to find the height of the tree after n days. If it dies, return -1.

So, if the input is like A = [0, 1, 1], then the output will be 7, because on the first day, it will not grow, so height is 1, after second day, the height will be 2, then after third day it will be 2 + 5 = 7.

Steps

To solve this, we will follow these steps −

r := 1
y := 0
n := size of A
for initialize i := 0, when i  0, then:
      r := -1
   y := x
return r

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;
int solve(vector A){
   int r = 1;
   int y = 0;
   int n = A.size();
   for (int i = 0; i  0)
         r = -1;
      y = x;
   }
   return r;
}
int main(){
   vector A = { 0, 1, 1 };
   cout 

Input

{ 0, 1, 1 }

Output

7
Updated on: 2022-03-15T06:56:23+05:30

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements