230220 다리를 지나는 트럭

Jongleee·2023년 2월 20일
0

TIL

목록 보기
186/737
public static 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;
}

0개의 댓글