Counting Valleys

Sort by

recency

|

190 Discussions

|

  • + 0 comments

    My Java solution:

     public static int countingValleys(int steps, String path) {
            int  currentLevel    = 0;
            char down            = 'D';
            int  numberOfValleys = 0;
    
            for (Character c : path.toCharArray()) {
                int step = c == down ? -1 : 1;
                if (currentLevel < 0 && (currentLevel + step) == 0) {
                    numberOfValleys++;
                }
                currentLevel += step;
            }
            return numberOfValleys;
        }
    
  • + 0 comments

    My Java solution:

    public static int countingValleys(int steps, String path) { int currentLevel = 0; char down = 'D'; int numberOfValleys = 0;

        for (Character c : path.toCharArray()) {
            int step = c == down ? -1 : 1;
            if (currentLevel < 0 && (currentLevel + step) == 0) {
                numberOfValleys++;
            }
            currentLevel += step;
        }
        return numberOfValleys;
    }
    
  • + 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;
        }
    
  • + 0 comments

    A valley is counted each time the hiker is at sea level and goes down. We just need to keep track of the current altitude to know that.

        public static int countingValleys(int steps, String path) {
            int numberOfValleys = 0;
            int position = 0;
            for(int i = 0; i<path.length(); i++){
                int direction = path.charAt(i) == 'U' ? 1 : -1;
                if(position == 0 && direction < 0){
                    numberOfValleys++;
                }
                
                position += direction;
            }
            
            return numberOfValleys;
        }
    
  • + 0 comments

    C++:

    int countingValleys(int steps, string path) {
        int count_ups = 0;
        int count_downs = 0;
        int total_valleys = 0;
        bool  is_valley= false;
        for(int i = 0; i < steps; i++)
        {
            (path[i] == 'D') ? ++count_downs : ++count_ups;
            int level = count_ups - count_downs;
            if(level < 0)
            {
                is_valley = true;
            }
            else if(is_valley && level == 0)
            {
                total_valleys++;
                is_valley = false;
            }
        }
        return total_valleys;
    }