프로그래머스 LEVEL 2(택배 상자)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-10-30

  • 해결 방법 :
    • 기존 컨테이너 벨트에서 숫자를 받아 바로 트럭에 실을지, 보조 컨테이너 벨트에 넣을지 확인
    • 기존 컨테이너 벨트를 모두 확인 후, 보조 컨테이너 벨트에서도 확인
  • 회고 :
    • x
  • 코드

    function solution(order) {
        let answer = 0;
        let index = 0;
        const stack = [];
            
        for (let i = 1; i <= order.length; i++) {
            if (order[index] === i) index++;
            else if (order[index] === stack[stack.length - 1]) {
                stack.pop();
                index++;
                i--;
            } else stack.push(i);
        }
            
        while (stack.length) {
            if (stack[stack.length - 1] === order[index]) {
                index++;
                stack.pop();
            } else break;
        }
            
        return index;
    }
    
  • 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges