• + 0 comments

    **Logic to solve the problem is if the previous step was a "U" and the sealevel count becomes 0 it is a valley. **

            int sealevel = 0;
            int valley = 0;
            char[] charPath = path.toCharArray();
            for (int i = 0; i < steps ; i++) {
                if (charPath[i]=='U'){
                    sealevel++;
                    if(sealevel==0) valley++;
                } 
                if (charPath[i]=='D') sealevel--;
            }
            return valley;
        }
    }