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.
A small Java solution in O(n) time with O(1) space:
//Java 8/*Initial Thoughts:Iterate over the ups and downs keeping track of your distance from sea level and whenever you makethe transition to below increase a value and repeatthat for each time you make the transitionTime Complexity: O(n) //We need to iterate over the whole hikeSpace Complexity: O(1) //We do no use any dynamically sized variables*/importjava.io.*;importjava.util.*;publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannerinput=newScanner(System.in);intn=input.nextInt();input.nextLine();Stringterrain=input.nextLine();intlevel=0;//Start at sea levelintvalleys=0;booleanbelowSea=false;for(inti=0;i<n;i++){charslope=terrain.charAt(i);if(slope=='U')//Uphilllevel++;else//Downhilllevel--;//Handle transitionsif(!belowSea&&level<0){valleys++;belowSea=true;}if(level>=0)//We are back above sea levelbelowSea=false;}System.out.println(valleys);}}
You can find more HackerRank solutions like this here
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 →
A small Java solution in O(n) time with O(1) space:
You can find more HackerRank solutions like this here