counting valleys hackerrank code example
Example 1: Counting Valleys
# HackerRank.com "Counting Valleys" problem
def countingValleys(n, s):
total_valley = 0
location = 0
for i in range(n):
if s[i] == 'D':
if location == 0:
total_valley = total_valley + 1
location = location - 1
continue
elif s[i] == 'U':
location = location + 1
return total_valley
Example 2: counting valleys hackerrank solution in c++
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,updown = 0,res = 0;
char c;
cin >> n;
for(int i = 0; i++ < n;){
cin >> c;
if(c == 'U')updown++;
else updown--;
if(updown == 0 && c == 'U')res++;
}
cout << res << endl;
return 0;
}
Example 3: the hiker first enters a valley 2 units deep
function countingValleys(n, s) { let level = 0; let result = 0; [...s].reduce((target, step) => { step.match(/u/i) ? level++ : level--; (!target && level >= 0) && (result++); target = !!(level >= 0); return target; }, true); return result;}