Counting Valleys [Hacker Rank]

Kim Hayeon·2023년 4월 25일
0

Algorithm Study

목록 보기
12/37
post-thumbnail

Question

An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps steps, for every step it was noted if it was an uphill,U , or a downhill,D step. Hikes always start and end at sea level, and each step up or down represents a 1 unit change in altitude. We define the following terms:

  • A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.

Code

def countingValleys(steps, path):
    # Write your code here
    v = 0 #to check valley
    answer = 0
    for i in range(steps):
        if path[i] == 'U':
            v += 1
            if v == 0: # if v turns - to 0
                answer += 1
        else:
            v -= 1
    return answer           
                

valley를 확인하기 위해 sea level보다 아래에서 sea level과 같아지면 answer에 +1 해준다.

profile
우리는 무엇이든 될 수 있어

0개의 댓글