• + 0 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) {

        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;
    
    }