문제설명
- 트럭 여러 대가 일차선 다리를 정해진 순으로 건넘
- 1초에 1만큼 움직이며 다리 길이는 bridge_length
- 다리는 무게 weight까지 견딤
- 트럭이 다리에 완전히 오르지 않은 경우, 이 트럭의 무게를 고려하지 않음
- 모든 트럭이 다리를 건러려면 최소 몇 초가 걸리는지 반환
제한조건
- bridge_length는 1이상 10,000이하
- weight는 1이상 10,000이하
- truck_weights의 길이는 1이상 10,000이하
- 모든 트럭의 무게는 1이상 weight이하
풀이
function solution(bridge_length, weight, truck_weights) {
let answer = 0;
let queSum = 0;
let que = [];
for(let i=0;i<bridge_length;i++){
que.push(0);
}
let nowTruck = truck_weights.shift();
que.unshift(nowTruck);
que.pop();
queSum += nowTruck;
++answer;
while(queSum){
queSum -= que.pop();
nowTruck = truck_weights.shift();
if(nowTruck + queSum <= weight){
que.unshift(nowTruck);
queSum += nowTruck;
}else{
truck_weights.unshift(nowTruck);
que.unshift(0);
}
++answer;
}
return answer;
}
+ 내가 해결했던 코드 추가
function solution(bridge_length, weight, truck_weights) {
const queue = new Array(bridge_length).fill(0);
let time = 0;
let nowWeight = 0;
queue.shift();
queue.push(truck_weights[0]);
nowWeight += truck_weights[0];
truck_weights.shift();
++time;
while (true) {
const initial = truck_weights.shift();
const out = queue.shift();
nowWeight -= out;
if (initial !== undefined) {
if (nowWeight + initial > weight) {
queue.push(0);
truck_weights.unshift(initial);
} else {
queue.push(initial);
nowWeight += initial;
}
}
++time;
if (truck_weights.length === 0) {
time += queue.length;
break;
}
}
return time;
}
체크포인트