We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Nice and simple solution. We can avoid String.toCharArray() and use just one if else as the String contains only 'U' and 'D'. Count how many times Gary moved to vally from sea level. Example-
static int countingValleys(int n, String s) {
int valleyCount = 0;
int currentState = 0;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i)=='U') {
currentState++;
} else {
currentState--;
// Moved from sea level to vally
if(currentState == -1){
valleyCount++;
}
}
}
return valleyCount;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Counting Valleys
You are viewing a single comment's thread. Return to all comments →
Nice and simple solution. We can avoid String.toCharArray() and use just one if else as the String contains only 'U' and 'D'. Count how many times Gary moved to vally from sea level. Example-
static int countingValleys(int n, String s) {