[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ฃผ์‹ ๊ฐ€๊ฒฉ ํ’€์ด
algorithm & data structure/coding test

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ฃผ์‹ ๊ฐ€๊ฒฉ ํ’€์ด

์ฃผ์‹๊ฐ€๊ฒฉ ๋ฌธ์ œ

์Šคํƒ

Last In First Out(LIFO), ๋‚˜์ค‘์— ๋“ค์–ด๊ฐ„ ์›์†Œ๊ฐ€ ๋จผ์ € ๋‚˜์˜ด push: ์Šคํƒ์— ์Œ“์Œ pop: ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์— ๋“ค์–ด๊ฐ„ ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋ฉฐ ๋ฐ˜ํ™˜

ํŒŒ์ด์ฌ ํ’€์ด

def solution(prices): st=[] answer = [0]*len(prices) for i in range(len(prices)): if st == []: st.append(i) continue else: if prices[i] >= prices[i-1]: st.append(i) else: while prices[i] < prices[i-1] : top = st.pop() answer[top] = i-top if st == []: st.append(i) break top = st.pop() st.append(top) if prices[i] >= prices[top] : st.append(i) break top = st.pop() st.append(top) while st != []: n=st.pop() answer[n] = top - n return answer

๊ทธ๋Ÿฐ๋ฐ ๋ณ„๋กœ.. ์ข‹์€ ์ฝ”๋“œ๋ผ๊ณ  ์ƒ๊ฐ์€ ์•ˆ ๋“ค์ง€๋งŒ ์–ด์จŒ๋“  ํ•ด๊ฒฐ

์ฐธ๊ณ ํ•œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค

prices = [3, 1, 2, 4, 2]
answer = [1, 3, 2, 1, 0]

ํ’€์ด ๋ฐฉ๋ฒ• (https://gurumee92.tistory.com/m/170 ์ฐธ๊ณ )

๋ฐ˜์‘ํ˜•