Counting Valleys

Sort by

recency

|

188 Discussions

|

  • + 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;
    }
    
  • + 0 comments
    function countingValleys(steps, path) {
        let i,temp=0,count=0;
        for(i=0; i<steps; i++){
            if(path[i]==="D"){
                temp--;
                
            }else{
                if(temp==-1){
                    count++;
                }
                temp++;
            }
        }
        
        return count;
    }
    
  • + 0 comments

    Python

    def countingValleys(steps, path):
        sea_level = 0
        total_valley_count = 0
        has_entered_valley = False
        for step in path:
            sea_level = sea_level + 1 if step == "U" else sea_level - 1 
            if sea_level < 0 and not has_entered_valley:
                has_entered_valley = True
            elif sea_level == 0 and has_entered_valley:
                has_entered_valley = False
                total_valley_count += 1
                
        return total_valley_count