다리를 지나는 트럭


프로그래머스 [다리를 지나는 트럭]

문제보기
Alt text

소스코드

import java.util.LinkedList;
import java.util.List;

class Solution {
     public static int solution(int bridge_length, int weight, int[] truck_weights) {
        int currentSecond = 0;
        int truckIdx = 0;

        long weightOnBridge = 0;
        List<Integer> timerList = new LinkedList<>();

        while (true) {
            currentSecond++;

            // 트럭이 다리를 빠져나갈 타이밍인지 확인
            int truckCnt = timerList.size();
            if (truckCnt != 0) {
                int timer = timerList.get(0);

                if (timer == currentSecond) {
                    timerList.remove(0);
                    weightOnBridge -= truck_weights[truckIdx - truckCnt];
                }
            }

            // 트럭이 다리에 지나갈 수 있는지 확인
            if (truckIdx < truck_weights.length) {
                int truckWeight = truck_weights[truckIdx];
                long checkWeight = weightOnBridge + truckWeight;

                if (checkWeight <= weight && timerList.size() < bridge_length) {
                    weightOnBridge = checkWeight;
                    timerList.add(currentSecond + bridge_length);
                    truckIdx++;
                }
            }


            if (timerList.isEmpty() && truckIdx >= truck_weights.length) break;
        }

        return currentSecond;
    }
}