• + 0 comments

    Java Solution

    Basic Understading: Valley when hiker at sea level after last step is U.

    public static int countingValleys(int steps, String path) {
        // Write your code here
            int valleys = 0, route = 0;
            char[] ch = path.toCharArray();
    
            for (int i = 0; i < steps; i++) {
    
                if ('U' == (ch[i]))
                    route += 1;
                else
                    route += -1;
    
                if (route == 0 && 'U' == ch[i]) // Basic Understanding
                    valleys++;
            }
    
            return valleys;
        }