2020 Updated Counting Valleys Hackerrank Solution in by Coding Demons



For better understanding refer YouTube Tutorial Video 

LOGIC:

  • Take array size (N)
  • Set variables to count valley (V=0) and check sea level (X=0)
  • Check the condition of below sea level or above sea level.
  • Check for uphill or downhill and act accordingly.
  • For uphill increment by 1, for downhill decrement by 1.
  • Repeat the steps till count ends.
  • Print the final valley count.


CODE:


/***SOLUTION BY CODING DEMONS***/


#include<bits/stdc++.h>
using namespace std;
int main () {

int n;   //array size 
cin>>n;            

char s;   //char to take one by one input
int x=0;  //variable to check sea level
int v=0;  //valley count

for (int i=0;i<n;i++){ 
  //loop executes till every char is checked

    cin>>s;
//input char
                                     
 if (x<0) {          
     //condition for below sea level 

 if (s=='U') x++; 
   //uphill increment x by 1

 else x--; 
 //downhill decrements x by 1

 if (x==0) v++;
  //sea level reached increment count by 1
}       
else {                 
//condition for above sea level 
if (s=='U') x++;
  //uphill increment x by 1

else x--; 
  //downhill decrements x by 1
  }                   
}                    
cout<<v<<endl;  
  //print final valley count

return 0;
}


/********END********/




    !! SUBSCRIBE FOR MORE CODES & VIDEOS !!

    Post a Comment

    0 Comments