Javascript :
function countingValleys(n, s) {
var seaLevel = 0, prevSeaLevel = 0, noOfValleys = 0;
if(s[0] == 'U'){
seaLevel = 1;
}else{
seaLevel = -1;
noOfValleys++;
}
for(var i = 1; i < n; i++){
prevSeaLevel = seaLevel;
if(s[i] == 'U'){
seaLevel++;
}else{
seaLevel--;
}
if(seaLevel < 0 && prevSeaLevel == 0){
noOfValleys++;
}
}
return noOfValleys;
}
Explanation:
For the first step of Gary’s hike, check if it is above or below sea level, if it < 0, add 1 to noOfValleys (Entering a valley in his 1st step, wow!)
The for loop begins with the 2nd element of the array s. This is needed to track the previous step’s sea level, so that if Gary is descending deeper into a valley, it does not count as a separate valley. Only when the prevSeaLevel is 0 does the noOfValley increases to ensure that Gary has stepped into a new valley.