231024 다리를 지나는 트럭

Jongleee·2023년 10월 24일
0

TIL

목록 보기
398/737
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

0개의 댓글