Counting Valleys

  • + 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