๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš€ Development/Problem Solving

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ฃผ์‹ ๊ฐ€๊ฒฉ(Lv.2) - ํŒŒ์ด์ฌ(Python)

by Jay Din 2024. 6. 19.
728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ์„ค๋ช…

์ดˆ ๋‹จ์œ„๋กœ ๊ธฐ๋ก๋œ ์ฃผ์‹๊ฐ€๊ฒฉ์ด ๋‹ด๊ธด ๋ฐฐ์—ด prices๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ๊ธฐ๊ฐ„์€ ๋ช‡ ์ดˆ์ธ์ง€๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”.

 

์ œํ•œ์‚ฌํ•ญ

  • prices์˜ ๊ฐ ๊ฐ€๊ฒฉ์€ 1 ์ด์ƒ 10,000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
  • prices์˜ ๊ธธ์ด๋Š” 2 ์ด์ƒ 100,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ

prices return
[1, 2, 3, 2, 3] [4, 3, 1, 1, 0]

 

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

  • 1์ดˆ ์‹œ์ ์˜ โ‚ฉ1์€ ๋๊นŒ์ง€ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.
  • 2์ดˆ ์‹œ์ ์˜ โ‚ฉ2์€ ๋๊นŒ์ง€ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.
  • 3์ดˆ ์‹œ์ ์˜ โ‚ฉ3์€ 1์ดˆ๋’ค์— ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง‘๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ 1์ดˆ๊ฐ„ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ๊ฒƒ์œผ๋กœ ๋ด…๋‹ˆ๋‹ค.
  • 4์ดˆ ์‹œ์ ์˜ โ‚ฉ2์€ 1์ดˆ๊ฐ„ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.
  • 5์ดˆ ์‹œ์ ์˜ โ‚ฉ3์€ 0์ดˆ๊ฐ„ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.

๋ฌธ์ œ ํ’€์ด

๋ฌธ์ œ์— ํ•ต์‹ฌ์€ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š๋Š” ๊ธฐ๊ฐ„์ด ๋ช‡ ์ดˆ ์ธ์ง€ ๊ตฌํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์ €๋Š” deque์— prices ๊ฐ’์„ ๋„ฃ์€ ํ›„, while๋ฌธ์—์„œ ํ•˜๋‚˜์”ฉ ๊ฐ’์„ ๋นผ์–ด ๋บ€ ๊ฐ’๋ณด๋‹ค ์ž‘์€ ๊ฐ’์ด ๋‚˜์˜ฌ ๋•Œ๊นŒ์ง€ ์ดˆ๋ฅผ ๋”ํ•ด์„œ ๋„ฃ์–ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.

์˜ˆ์‹œ์—์„œ prices์˜ 3๋ฒˆ์งธ ๊ฐ’์ธ 3์€ ๋‹ค์Œ ๊ฐ’์ด 2์ด๊ธฐ ๋•Œ๋ฌธ์— 1์ดˆ๋™์•ˆ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•„ ๊ฐ’์ด 1์ด ๋ฉ๋‹ˆ๋‹ค.

from collections import deque

def solution(prices):
    answer = []
    queue = deque(prices)   
    
    while queue:
        price = queue.popleft()
        sec = 0
        
        for i in queue:
            sec+=1
            if price > i:
                break
                
        answer.append(sec)
        
                             
    return answer
728x90
๋ฐ˜์‘ํ˜•