Counting Valleys

 Given the sequence of up and down steps during a hike, find and print the number of valleys walked through. 

ip:

8
UDDDUDUU
op:
1 
_/\      _
   \    /
    \/\/ 

 

int countingValleys(int n, string s) {
  int level=0;
  int valley=0;
  
  for(auto c: s)
  {
      if(c=='U')
      {
          if(level==-1)
          {
              valley++;
          }
          level++;
      }
      else{
          level--;
      }
  }
  
  return valley;
}

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!