상세 컨텐츠

본문 제목

다리를 지나는 트럭 (스택/큐)

프로그래머스 코딩테스트 풀이

by 발발개발 2022. 7. 11. 11:09

본문

원본 : https://school.programmers.co.kr/learn/courses/30/lessons/42583

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

풀이

import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        Queue<Integer> truckQueue = new LinkedList<>();
        Queue<int[]> bridgeQueue = new LinkedList<>();

        for (int w : truck_weights) {
            truckQueue.add(w);
        }

        int time = 0;

        while (!(truckQueue.isEmpty() && bridgeQueue.isEmpty())) {
            time++;
            bridgeQueue.forEach(bridgeArr -> bridgeArr[1]++);

            if (!bridgeQueue.isEmpty() && bridgeQueue.peek()[1] == bridge_length) {
                bridgeQueue.poll();
            }

            if (bridgeQueue.isEmpty() && !truckQueue.isEmpty()) {
                bridgeQueue.add(new int[]{truckQueue.poll(), 0});
            } else {
                int weightSum = 0;
                for (int[] arr : bridgeQueue) {
                    weightSum += arr[0];
                }
                if (!truckQueue.isEmpty() && weightSum + truckQueue.peek() <= weight) {
                    bridgeQueue.add(new int[]{truckQueue.poll(), 0});
                }
            }
        }

        return time;
    }
}

'프로그래머스 코딩테스트 풀이' 카테고리의 다른 글

카펫 (완전탐색)  (0) 2022.07.14
H-Index (정렬)  (0) 2022.07.14
위장 (해시)  (0) 2022.07.11
2 x n 타일링 (연습문제)  (0) 2022.07.08
배달 (Summer/Winter Coding(~2018))  (0) 2022.07.08

관련글 더보기

댓글 영역