• + 0 comments

    My solutions in Java:

    1:

        public static int countingValleys(int steps, String path) {
        
            int seaLevel = 0;
            int valleys = 0;
            boolean isInValley = false;
            for (int i = 0; i < steps; i++) {
                if(path.charAt(i) == 'U'){
                    seaLevel++;
    
                } else {
                    seaLevel--;
                }
                
                if(seaLevel < 0) {
                    isInValley = true;
                } else if (seaLevel > 0){
                    isInValley = false;
                }
                
                if(seaLevel == 0 && isInValley) {
                    valleys++;
                }
                
            }
            
            return valleys;
        }
    

    2: more concise

    public static int countingValleys(int steps, String path) {
    
        int seaLevel = 0;
        int valleys = 0;
        for (char step : path.toCharArray()) {
           seaLevel += (step == 'U') ? 1 : -1;
    
            // Detect if a valley has been exited
           if (seaLevel == 0 && step == 'U') {
             valleys++;
           }
        }
    
        return valleys;
    }
    

    sd