 #1
 237
 78
Homework Statement:

I am working on improving my programming and/or problem solving aptitude. I am currently trying to solve the problem the following page.
The program should count the number of valleys traversed. Please visit the link for more details
https://www.hackerrank.com/challenges/countingvalleys/problem?h_l=interview&playlist_slugs%5B%5D=interviewpreparationkit&playlist_slugs%5B%5D=warmup
Relevant Equations:

s = [UDDDUDUU] "U" stands for up and "D" for down
in the above example the number of valleys is 1
_/\ _
\ /
\/\/
// Complete the countingValleys function below.
// The code is in javaScript
Right now, my code is passing 18 of the 22 test cases.
The remaining cases are
10
[DUDDDUUDUU]
100
[DUDUUUUUUUUDUDDUUDUUDDDUUDDDDDUUDUUUUDDDUUUUUUUDDUDUDUUUDDDDUUDDDUDDDDUUDDUDDUUUDUUUDUUDUDUDDDDDDDDD]
1000
[DUDUUDUUUUUUDDDDDUDDUUUDUUUDDDUUUDDUDDDDUDDDDDUUDUDUDUDDDDUUDDUDDUUUUDDUUUUDUUDUUDUUUUDDDUDDUUUUDUDDDUUDUDUUDDUUUDUDDDUDUDUDUDUUUDUUUUUUDUDDDDDUDUDDDDUUUUUDUDUUUUUUUUDDDUUDUUDUDUDDDDDUDDDUDUUUDUDDDUDUUDUUDDDDDDDUDUDUUUDUDDUDUUDUDDDUUUDUDDDDUDDUDDUDUDUUDUDDDUDUUUDUUDUUUUUUUDUUUUUUUDDDDDUDDDUUUDDDUDDDUDDUUDDUUUDUUDDDUDUUDUUUDDUDDDDUUUUUUDUDUUDDDDUDUDDUUUDUDUUDDUUDDDUUDUUUUUDDUUDDDDUUUDUDUUDDUUDDUUDUDDDUDUDUDDUUDUDDUDUDDUUUDUDDUDDUUDUUDUDDDDDDDDDUDDUUDDUUUUDDUDUUDUUDUUDDDDUUUDUDDDDUDDUUDUDUDUUDDUUDUDUDDDDDUUUDDDDUDDDUUDDUUDDUUUDUDDDUDDDDDUUDUUUDDUDDDDUUUDDDDUUDDUUUDUUUDDUDUUUDUDDUUUDDDDDDDUUDDUDDUUUUUUDDDDUDDUDDUDDUDDDDDUUDDUDDDUDDUDUDDDUDUDUUDDUUDDDDUUDDUUUDUUDDDDDDUDUDDUDUUDDUDDDUUUUDDUUDUDDDDUUUDUUUUDDUDUUUDDUDUUUUUUDUUDDDDDUDDUDUDDDUDDDDUDUUUDUDUUDDUDDDUDUUDDDDDDDDUDUUDUDDUDDUDUUUDDDUDUDDUUUDUDUDDDUDDUDUUUDUDDDDDUDDDDDDUDUUUUDDUDDDUDDDUDUDUUUDDUDDUDDUUDDUDUDUDUUUUUDUUDDUUDUUDUUUDUDUDDUDDDUUDDDDUUDDUUUUDUUDUUUDDDDDUDDDDDUUUDDUUUDUUUDUUDUUUDUDUUDUDDUUUUUDUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU]
1000000
[ too big to put here (1 million) ][/I][/I][/I][/I][/I]
// The code is in javaScript
JavaScript:
function countingValleys(n, s) {
let currentLevel = [] // an array of numbers that indicate the number of units of altitude above or below sea level regarding each step
let altitude = 0 // the altitude above sea level
let valleyCount = 0; // count of the number of valleys
for (let i = 0; i < s.length; i++) {
if(s[I] === 'U') {
altitude++
currentLevel.push(altitude)
}
else {
altitude
currentLevel.push(altitude)
}
if(i >= 2) {
if(currentLevel[I] === 0 && currentLevel[i1] < 0
&& currentLevel[i2] <= 0) {
valleyCount++
}
else if(currentLevel[i+1] < currentLevel[I] && currentLevel[I] < 0 &&
currentLevel[i1] < currentLevel[I] &&
currentLevel[i2] < currentLevel[i1]) {
valleyCount++
}
}
}
return valleyCount
}
The remaining cases are
10
[DUDDDUUDUU]
100
[DUDUUUUUUUUDUDDUUDUUDDDUUDDDDDUUDUUUUDDDUUUUUUUDDUDUDUUUDDDDUUDDDUDDDDUUDDUDDUUUDUUUDUUDUDUDDDDDDDDD]
1000
[DUDUUDUUUUUUDDDDDUDDUUUDUUUDDDUUUDDUDDDDUDDDDDUUDUDUDUDDDDUUDDUDDUUUUDDUUUUDUUDUUDUUUUDDDUDDUUUUDUDDDUUDUDUUDDUUUDUDDDUDUDUDUDUUUDUUU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