[Programmers / Level 2] 42583. 다리를 지나는 트럭 (Java)

이하얀·2025년 1월 25일
0

🕊️ 프로그래머스

목록 보기
94/97

💡 Info




입출력 조건




입출력 예시




문제 이해




알고리즘


풀이 시간 : 18분

  • 초기화
    • 다리 Queue -> 길이만큼 0을 채우는 방식
    • totalWeight = 0, time = 0, index = 0
  • while문으로 트럭 이동
    • time++
    • 다리에서 트럭 제거 -> totalWeight 감소
    • 새 트럭이 다리에 올라갈 수 있으면 추가 (totalWeight + 트럭 무게 <= 하중)
    • 못 올라가면 0 추가 (continue로 다음 루프)
  • 마지막 트럭이 다리 건너는 시간 추가
import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        Queue<Integer> bridge = new LinkedList<>();
        int totalWeight = 0, time = 0, index = 0;

        for (int i = 0; i < bridge_length; i++) {
            bridge.offer(0);
        }

        while (index < truck_weights.length) {
            time++;
            totalWeight -= bridge.poll();
            if (totalWeight + truck_weights[index] > weight) {
                bridge.offer(0);
                continue;
            }
            bridge.offer(truck_weights[index]);
            totalWeight += truck_weights[index];
            index++;
        }
        
        return time + bridge_length;
    }
}


결과


profile
언젠가 내 코드로 세상에 기여할 수 있도록, BE&Data Science 개발 기록 노트☘️

0개의 댓글

관련 채용 정보