ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/

 

StoneWall coding task - Learn to Code - Codility

Cover "Manhattan skyline" using the minimum number of rectangles.

app.codility.com

 


๋ฌธ์ œ ํ’€์ด

๊ฐ ๋Œ์˜ ๋†’์ด๊ฐ€ ์ฃผ์–ด์ง€๊ณ , ๋Œ๋‹ด์„ ๊ตฌ์„ฑํ•˜๊ธฐ ์œ„ํ•œ ์ตœ์†Œ์˜ ๋Œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

stack์„ ์ด์šฉํ•˜์—ฌ, stack[-1]์˜ ๊ฐ’์ด ํ˜„์žฌ ๋Œ์˜ ๋†’์ด ๋ณด๋‹ค ๋‚ฎ์œผ๋ฉด ๊ธฐ์ค€์„ ํ˜„์žฌ๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค.

stack[-1]์ด ํ˜„์žฌ ๋Œ์˜ ๋†’์ด๋ณด๋‹ค ๋†’์œผ๋ฉด ์นด์šดํŠธ๋ฅผ ์ฆ๊ฐ€ํ•˜๊ณ  ์Šคํƒ์— ์ถ”๊ฐ€ํ•˜๊ณ  ๋ฐ˜๋Œ€์ผ ๊ฒฝ์šฐ ๋†’์ด๊ฐ€ ํด ๋•Œ๊นŒ์ง€ stack.pop() ์„ ์ง„ํ–‰ํ•œ๋‹ค.


์ฝ”๋“œ

def solution(H):
    stack = []
    cnt = 0
    for stone_size in H:
        while len(stack) > 0 and stack[-1] > stone_size:
            stack.pop()
        if not stack or stack[-1] < stone_size:
            stack.append(stone_size)
            cnt += 1
    return cnt

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€