Hackerrank Counting Valleys Problem Solution

HackerRank Counting Valleys Problem Solution in C

#include<stdio.h>
int main()
{
  int n,valley=0,i;
  scanf("%d",&n);
  char arr[n];
  scanf("%s",arr);
  int level = 0;
  int starts=0;
  for(i=0;i<n;i++)
  {

    if(level == 0 && arr[i] == 'D')
    {
      starts=1;
    }
    if(level==0 && starts==1)
    {
      starts=0;
      valley++;
    }
    if(arr[i]=='U')
    {
      level+=1;
    }
    else if(arr[i] == 'D')
    {
      level-=1;
    }
  }
  printf("%d",valley);
}

HackerRank Counting Valleys Problem Solution in C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int test, sum = 0, count = 0;
    char c;
    bool flag = 1;
    cin >> test;
    c = getchar();
    while(test--)
    {
        c = getchar();
        if(c == 'U')
            ++sum;
        else if(c == 'D')
            --sum;
        if(sum == 0)
            flag = 1;
        else if(flag && sum < 0)
        {
            ++count;
            flag = 0;
        }
    }
    printf("%d", count);
    return 0;
}

HackerRank Counting Valleys Problem Solution in Javascript

function processData(input) {
    input = input.split('\n');
    var walk = input[1].split('');
    
    var count = 0;
    var sea = true;
    var valleys = 0;
    
    walk.forEach((step)=>{
        if(step==='U'){
            count++;
        } else {
            count--;
        }
        
        if(count === 0){
            sea = true;
        } else if (count!== 0 && sea === true){
            sea = false;
            if(count<0){
                valleys++;
            }
        }
    });
    console.log(valleys);
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

0 Comments