-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounting_Valleys.cpp
49 lines (37 loc) · 891 Bytes
/
Counting_Valleys.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Hackerrank.com
// Practice > Interview Preparation Kit > Warm-up Challenges > Counting Valleys
#include <iostream>
#include <string>
using namespace std;
int countingValleys(string s, int n);
int main() {
string s;
int n;
cin >> n; // Length of string.
cin >> s; // Get String.
int result;
result = countingValleys(s, n);
cout << result << endl;
}
int countingValleys(string s, int n) {
int res = 0; // variable for counting number of valleys.
int c = 0; // check level variable.
int down = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'U')
c += 1;
if (s[i] == 'D')
{
if (c == 0)
{
down = 1; // "1" indicates, entered into a valley.
}
c -= 1;
}
if (down == 1 && c == 0) {
res += 1;
down = 0; // "0" indicates, coming out of the valley.
}
}
return res;
}