forked from RyanFehr/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
47 lines (41 loc) · 1.41 KB
/
Solution.java
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
//Problem: https://www.hackerrank.com/challenges/counting-valleys
//Java 8
/*
Initial Thoughts:
Iterate over the ups and downs keeping track of
your distance from sea level and whenever you make
the transition to below increase a value and repeat
that for each time you make the transition
Time Complexity: O(n) //We need to iterate over the whole hike
Space Complexity: O(1) //We do no use any dynamically sized variables
*/
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
int n = input.nextInt(); input.nextLine();
String terrain = input.nextLine();
int level = 0; //Start at sea level
int valleys = 0;
boolean belowSea = false;
for(int i = 0; i < n; i++)
{
char slope = terrain.charAt(i);
if(slope == 'U')//Uphill
level++;
else//Downhill
level--;
//Handle transitions
if(!belowSea && level < 0)
{
valleys++;
belowSea = true;
}
if(level >= 0)//We are back above sea level
belowSea = false;
}
System.out.println(valleys);
}
}