Counting Valleys Code Challenge Solved

unsuredev

Jamal

Posted on June 29, 2020

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") {
        --e;
    } else if (s[i] === "U") {
        if (++e === 0) travel++;
    }
}
return travel;
Enter fullscreen mode Exit fullscreen mode

}

Here Link
full details here: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup

💖 💪 🙅 🚩
unsuredev
Jamal

Posted on June 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Counting Valleys Code Challenge Solved