From 1eb9eff16530ffbde3be5eb6dfa84e72cfac4d85 Mon Sep 17 00:00:00 2001 From: Jungwoo Lee <87072568+howooking@users.noreply.github.com> Date: Tue, 14 May 2024 09:12:25 +0900 Subject: [PATCH] =?UTF-8?q?[pgm]=20=EC=A3=BC=EC=8B=9D=EA=B0=81=EA=B2=A9=20?= =?UTF-8?q?/=20level2=20/=20=EB=AA=BB=ED=92=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...74\354\213\235\352\260\201\352\262\251.js" | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 "howoo/\354\243\274\354\213\235\352\260\201\352\262\251.js" diff --git "a/howoo/\354\243\274\354\213\235\352\260\201\352\262\251.js" "b/howoo/\354\243\274\354\213\235\352\260\201\352\262\251.js" new file mode 100644 index 0000000..2ceb68b --- /dev/null +++ "b/howoo/\354\243\274\354\213\235\352\260\201\352\262\251.js" @@ -0,0 +1,34 @@ +function solution(prices) { + const n = prices.length; + const answer = new Array(n).fill(0); + + // 특정 조건의 prices의 인덱스를 담는 스택 + const stack = []; + + for (let i = 0; i < n; i++) { + // 스택의 길이가 0보다 크고, 현재 선택한 가격보다 스택의 마지막 요소의 인덱스의 가격이 크면(가격이 떨어졌다는 의미) + while (stack.length > 0 && prices[stack[stack.length - 1]] > prices[i]) { + // 가격이 떨어진 인덱스를 없에고 변수에 담음 + const idx = stack.pop(); + // 정답 배열에 현재 i에서 가격이 떨어진 인덱스의 가격을 빼서 저장 + answer[idx] = i - idx; + } + stack.push(i); + } + + // 위 단계 까지 진행하면 + // stack에는 [0, 1, 3, 4] + // answer에는 [0, 0, 1, 0, 0] + // 이 담겨 있음 + + // answer에 0이 담겼다는 것은 가격이 내려가지 않았다는 의미 + + while (stack.length > 0) { + const idx = stack.pop(); + answer[idx] = n - idx - 1; + } + + return answer; +} + +console.log(solution([1, 2, 3, 2, 3]));