Hacker Rank Counting Valleys

x·2021년 4월 26일
0

problem-solving

목록 보기
3/18

문제 이름 그대로 valley를 세서 응답하면 된다
문제에서 정의한 mountain, valley는 다음과 같다
mountain : sea level(해발고도)에서부터 위로 갔다가 해발고도로 내려오는 것
valley : sea level에서부터 아래로 내려갔다가 해발고도로 오는 것

결국 해발 고도는 0이고 0 미만이 되었다가 다시 0으로 오는 시점마다 valley를 누적해서 응답하면 된다

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'countingValleys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER steps
#  2. STRING path
#

def countingValleys(steps, path):
    valley_flag = False
    s = 0
    result = 0
    for p in path:
        v = 1 if p == "U" else -1
        s += v
        if s < 0 :
            valley_flag = True
        
        if s >= 0 and valley_flag == True:
            result += 1
            valley_flag = False
        
    return result
    
if __name__ == '__maiㅃn__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    steps = int(input().strip())

    path = input()

    result = countingValleys(steps, path)

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

    fptr.close()

https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup

0개의 댓글