public int solution(int bridgeLength, int weight, int[] truckWeights) {
Queue<Integer> waitingTrucks = new LinkedList<>();
for (int truckWeight : truckWeights) {
waitingTrucks.add(truckWeight);
}
int elapsedTime = 0;
int currentBridgeWeight = 0;
Queue<Integer> trucksOnBridge = new LinkedList<>();
Queue<Integer> enteredTimes = new LinkedList<>();
while (!waitingTrucks.isEmpty() || !trucksOnBridge.isEmpty()) {
elapsedTime++;
if (!trucksOnBridge.isEmpty() && elapsedTime - enteredTimes.peek() >= bridgeLength) {
currentBridgeWeight -= trucksOnBridge.poll();
enteredTimes.poll();
}
if (!waitingTrucks.isEmpty() && currentBridgeWeight + waitingTrucks.peek() <= weight) {
int currentTruckWeight = waitingTrucks.poll();
currentBridgeWeight += currentTruckWeight;
trucksOnBridge.add(currentTruckWeight);
enteredTimes.add(elapsedTime);
}
}
return elapsedTime;
}
출처:https://school.programmers.co.kr/learn/courses/30/lessons/42583