[백준] 2493 탑 nodejs

DongDong·2024년 1월 16일
0

https://www.acmicpc.net/problem/2493

해당 문제는 제일 큰 값보다 이전에 나온 작은 값들이 쓸모가 없어지는 것을 아는 것이 중요한 것 같다.

// [골드5] https://www.acmicpc.net/problem/2493
// let input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
let input = require("fs")
  // .readFileSync("./input.txt")
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split("\n");

function getResult() {
  const length = Number(input[0]);
  const towers = input[1].split(" ").map(Number);
  // stack에 [ value, index ] 형태로 담아둔다.
  const stack = [];
  // 초기 결과값 배열 생성
  // [ 0, 0, 0, 0, ... ]
  const result = new Array(length).fill(0);

  for (let i = 0; i < length; i++) {
    // 스택이 비어있지 않고
    // towers(input)의 값이 스택의 제일 끝방의 값보다 클 때
    // 스택에 있는 값들을 모조리 pop 해주기.
    // 현재 탑(towers[i])보다 높거나 같은 첫 번째 탑을 찾을 때까지 스택에서 탑들을 제거
    while (stack.length > 0 && stack[stack.length - 1][0] < towers[i]) {
      stack.pop();
    }
    // 스택이 비어있지 않은 경우
    // 결과값을 담는 배열에 스택의 제일 끝방의 인덱스를 넣어준다.
    if (stack.length > 0) {
      result[i] = stack[stack.length - 1][1];
    }
    stack.push([towers[i], i + 1]);
  }

  return result.join(" ");
}

console.log(getResult());
profile
중요한건 꺾이지 않는 마음

0개의 댓글

관련 채용 정보