본문 바로가기

TIL/Algorithm

[Algorithm] Hackerrank - Counting Valleys

반응형

문제:

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly  steps. For every step he took, he noted if it was an uphill, , or a downhill,  step. Gary's hikes start and end at sea level and each step up or down represents a  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 Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is , he first enters a valley  units deep. Then he climbs out an up onto a mountain  units high. Finally, he returns to sea level and ends his hike.

Function Description

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys has the following parameter(s):

  • n: the number of steps Gary takes
  • s: a string describing his path

Input Format

The first line contains an integer , the number of steps in Gary's hike. 
The second line contains a single string , of  characters that describe his path.

 

Output Format

Print a single integer that denotes the number of valleys Gary walked through during his hike.

Sample Input

8

UDDDUDUU

Sample Output

1

Explanation

If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:

_/\          _

    \       /

      \/\/

He enters and leaves one valley.

코드:

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the countingValleys function below.
def countingValleys(n, s):
    high = 0
    count = 0
    for i in s:
        if i == 'D':
            high -= 1
        else:
            high += 1
            if high == 0:
                count += 1
    return count

    return count

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    s = input()

    result = countingValleys(n, s)

    fptr.write(str(result) + '\n')

    fptr.close()

코드설명:

문제는 일단 골짜기 수를 세는것. 지면에서 아래로 내려오고 다시 지면과 동일해질때 이를 한개의 골짜기라고 함

즉 단순히 s.count('DUD')를 한다고 해서 풀리는게 아님. DUUDD 도 한개의 골짜기.

 

따라서 주어진 스트링에서 높이를 지정하는 high 변수를 설정해서, D가 나오면 -1, U가 나오면 1을 추가하는 형식으로 진행. 그리고 만일 U가 나왔고, high가 다시 0이됐을때 이는 골짜기가 형성됐으므로 count에 1을 추가해준다.

반응형