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 < n, update (increase i by 1), do:
   x := A[i]
   if r is same as -1, then:
      Ignore following part, skip to the next iteration
   if x is non-zero and y is non-zero, then:
      r := r + 5
   otherwise when x is non-zero, then:
      (increase r by 1)
   otherwise when not x is non-zero and not y is non-zero and i > 0, then:
      r := -1
   y := x
return r

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int r = 1;
   int y = 0;
   int n = A.size();
   for (int i = 0; i < n; ++i){
      int x = A[i];
      if (r == -1)
         continue;
      if (x && y)
         r += 5;
      else if (x)
         ++r;
      else if (!x && !y && i > 0)
         r = -1;
      y = x;
   }
   return r;
}
int main(){
   vector<int> A = { 0, 1, 1 };
   cout << solve(A) << endl;
}

Input

{ 0, 1, 1 }

Output

7

Updated on: 15-Mar-2022

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements