DEV Community 👩‍💻👨‍💻

Jamaluddin Mondal
Jamaluddin Mondal

Posted on

Counting Valleys Code Challenge Solved

A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is s=[DDUUUUDD], he first enters a valley 2 units deep. Then he climbs out and up into a mountain 2 units high. Finally, he returns to sea level and ends the hike.
Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly n steps.

For every step he took, he noted if it was an uphill, U, or a downhill, D step. Gary's hikes start and end at sea level and each step up or down represents a 1 unit change in altitude.

On Hackerrank change this function :JavaScript

function countingValleys(n, s) {

let e= 0;
let travel = 0;
for (let i = 0; i < n; i++) {
    if (s[i] === "D") {
    } else if (s[i] === "U") {
        if (++e === 0) travel++;
return travel;
Enter fullscreen mode Exit fullscreen mode


Here Link
full details here:

Top comments (0)

🤔 Did you know?

🗺 We put together some guides that include some of our favorite content on DEV. Check them out here.