Counting Valleys

  • + 0 comments

    A valley is counted each time the hiker is at sea level and goes down. We just need to keep track of the current altitude to know that.

        public static int countingValleys(int steps, String path) {
            int numberOfValleys = 0;
            int position = 0;
            for(int i = 0; i<path.length(); i++){
                int direction = path.charAt(i) == 'U' ? 1 : -1;
                if(position == 0 && direction < 0){
                    numberOfValleys++;
                }
                
                position += direction;
            }
            
            return numberOfValleys;
        }