Counting Valleys

  • + 0 comments

    In C#

    public static int countingValleys(int steps, string path)
        {
            if((steps < 2 || steps > Math.Pow(10, 6)) && !path.Contains('U') || !path.Contains('D')) throw new Exception("Pasos invaldos");
            
            
            int countVa = 0;
            
            int level = 0;
    
            for(int i = 0; i<steps; i++){
                
                if(path[i] == 'U') level++;
                if(path[i] == 'D') level--;
                
                if(path[i] == 'U' && level == 0) countVa++;
            }
            
            return countVa;
        }