https://school.programmers.co.kr/learn/courses/30/lessons/42584

 

๋ฌธ์ œ

 

๋ฌธ์ œ ์„ค๋ช…

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

 

 

์ œํ•œ ์‚ฌํ•ญ

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

 

์ž…์ถœ๋ ฅ ์˜ˆ

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

 

 

์†Œ์Šค ์ฝ”๋“œ
# 1
def solution(prices):
    n = len(prices)
    answer = []

    for i in range(n):
        idx = 0
        for j in range(i+1,n):
            if prices[j] < prices[i]:   # ํ˜„์žฌ ์ฃผ์‹๊ฐ€๊ฒฉ๋ณด๋‹ค ๋–จ์–ด์ง„ ๊ฒฝ์šฐ
                idx = j                 # ๋–จ์–ด์ง„ ์‹œ์ ์„ idx์— ์ €์žฅํ•˜๊ณ  ์ข…๋ฃŒ
                break

        if idx==0:                      # ํ˜„์žฌ ์ฃผ์‹๊ฐ€๊ฒฉ์—์„œ ๋–จ์–ด์ง€์ง€ ์•Š์€ ๊ฒฝ์šฐ
            answer.append(n-i-1)        # ์ „์ฒด ๊ธธ์ด์—์„œ ํ˜„์žฌ ์ธ๋ฑ์Šค๋ฅผ ๋บ€ ๊ฐ’
        else:
            answer.append(idx-i)        # ๋–จ์–ด์ง„ ์‹œ์ ์—์„œ ํ˜„์žฌ ์ธ๋ฑ์Šค๋ฅผ ๋บธ ๊ฐ’

    return(answer)

 

ํ’€์ด # 1

  • ํ˜„์žฌ์˜ ์ฃผ์‹๊ฐ€๊ฒฉ์€ i๋ฒˆ์งธ์— ์žˆ๋Š” ๊ฐ’์ด๊ณ  ๋‚˜๋จธ์ง€ ์ฃผ์‹๊ฐ€๊ฒฉ์€ j๋ฒˆ์งธ์— ์žˆ๋Š” ๊ฐ’
  • ํ˜„์žฌ ์ฃผ์‹๊ฐ€๊ฒฉ๊ณผ ๋‚˜๋จธ์ง€ ์ฃผ์‹๊ฐ€๊ฒฉ์„ ๋น„๊ตํ•ด์„œ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€๋Š” ์‹œ์ ์„ idx์— ์ €์žฅ
    • ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์กŒ๋‹ค๋ฉด for๋ฌธ ๋น ์ ธ๋‚˜์˜ค๊ธฐ
  • idx๊ฐ€ 0์ด๋ฉด ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์€ ๊ฒƒ์ด๋ฏ€๋กœ ์ „์ฒด๊ธธ์ด์—์„œ ํ˜„์žฌ ์ฃผ์‹๊ฐ€๊ฒฉ์˜ ์ธ๋ฑ์Šค ๋นผ๊ธฐ
  • idx๊ฐ€ 0์ด ์•„๋‹ˆ๋ฉด ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง„ ์‹œ์ ์ด idx์ด๋ฏ€๋กœ ๋–จ์–ด์ง„ ์‹œ์ ์—์„œ ํ˜„์žฌ ์ธ๋ฑ์Šค ๋นผ๊ธฐ

 

# 2
def solution(prices):
    n = len(prices)
    answer = [0] * n     

    for i in range(n):
        for j in range(i+1, n):
            answer[i] += 1
            if prices[i] > prices[j]:   # ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง„ ๊ฒฝ์šฐ
                break                   # for๋ฌธ ์ข…๋ฃŒ

    return answer

 

ํ’€์ด #2

  • ์ฃผ์‹๊ฐ€๊ฒฉ ๊ธธ์ด๋งŒํผ์˜ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
  • ํ˜„์žฌ ์ฃผ์‹๊ฐ€๊ฒฉ์€ i๋ฒˆ์งธ์— ์žˆ๋Š” ๊ฐ’์ด๊ณ  ๋‚˜๋จธ์ง€ ์ฃผ์‹๊ฐ€๊ฒฉ์€ j๋ฒˆ์งธ์— ์žˆ๋Š” ๊ฐ’
  • answer ๋ฆฌ์ŠคํŠธ์— 1์„ ๋”ํ•˜๊ณ  ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์กŒ๋‹ค๋ฉด for๋ฌธ์„ ์ข…๋ฃŒ
    • ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€์ง€ ์•Š์•˜๋‹ค๋ฉด for๋ฌธ์œผ๋กœ ๋Œ๋ฉด์„œ +1 ์—ฐ์‚ฐ์„ ์ง„ํ–‰

 

์ฒ˜์Œ์—๋Š” ๋ฌธ์ œ ์ดํ•ด๊ฐ€ ์•ˆ๋์—ˆ๋Š”๋ฐ ๋‹จ์ˆœํ•˜๊ฒŒ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ํ˜„์žฌ ์ธ๋ฑ์Šค ๊ฐ’๊ณผ ๋‚˜๋จธ์ง€ ์ธ๋ฑ์Šค ๊ฐ’์„ ๋น„๊ตํ•ด์„œ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€๊ธฐ ์ „๊นŒ์ง€ ์‹œ๊ฐ„์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์˜€๋‹ค. ์ •ํ™•๋„์™€ ํšจ์œจ์„ฑ์„ ๋ชจ๋‘ ํ…Œ์ŠคํŠธํ•˜๋Š” ๋ฌธ์ œ๋ผ์„œ ์–ด๋ ต๊ฒŒ ์ƒ๊ฐํ–ˆ์—ˆ๋Š”๋ฐ ํ•„์š”์—†๋Š” ์—ฐ์‚ฐ์„ ์ง€์šฐ๊ณ  ์ฃผ์‹๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€๋Š” ์ˆœ๊ฐ„๊นŒ์ง€๋งŒ ์—ฐ์‚ฐ์„ ์ง„ํ–‰ํ•˜๋‹ˆ ์˜์™ธ๋กœ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

+ Recent posts