DEV Community

duccanhole
duccanhole

Posted on

code every day with me

--DAY 17--

Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:

  • Problem: Counting Valleys
  • Detail: here
  • Idea : we only care below part, if we reach to the sea level, it means we that's valleys.
    • ex : UDDDUDUU
    • If we represent _ as sea level, a step up as /, and a step down as \, the hike can be drawn as:
_/\      _
   \    /
    \/\/
Enter fullscreen mode Exit fullscreen mode
  • We only care about below part, so the number the hiker reach to the sea level is 1.
    • My solution (javascript):
function countingValleys(steps, path) {
    let count=0,lv=0;
    for(let i in path){
        if(path[i]=='U'){
            lv++;
            if(lv==0) count++;
        }
        else lv--;
    }
    return count;
}
Enter fullscreen mode Exit fullscreen mode

-->If you have better solution or any question, please comment below. I will appreciate.

Top comments (0)