알고리즘

프로그래머스 다리를 지나는 트럭 (JAVA)

박카스마시며코딩 2023. 8. 18. 14:41

https://school.programmers.co.kr/learn/courses/30/lessons/42583#

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

저는 큐를 이용해 문제를 해결하였습니다.

큐를 이용해 다리에 몇 개의 트럭이 존재하는지를 확인하였고, 큐의 무게 합이 weight보다 크거나, 큐의 길이가 bridge_length보다 길다면 큐에서 하나씩 빼주면서 해당 값의 시작 시간 + bridge_length를 하여 해당 트럭이 다 건넌 시간 와 현재 시간을 비교하여 더 큰 값으로 시간을 초기화하여 문제를 해결하였습니다. 

 

import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        int time = 1;
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{truck_weights[0],0});
        int sum = truck_weights[0];
        int index = 1;
        while(index < truck_weights.length){
            while(!q.isEmpty() && (sum + truck_weights[index] > weight || q.size() >= bridge_length) ){
                int[] temp = q.poll();
                time = Math.max(temp[1] + bridge_length,time);
                sum -= temp[0];
            }
            sum += truck_weights[index];
            q.offer(new int[]{truck_weights[index],time});
            time++;
            index++;
        }
        while(!q.isEmpty()){
            int[] temp = q.poll();
            time = temp[1] + bridge_length;
        }
        answer = time + 1;
        return answer;
    }
}