티스토리 뷰

1Day 1Algorithm

[DAY 27] Truck tour

walk_through_me 2019. 10. 27. 23:32

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N - 1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump.

Initially, you have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps. Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol.

 

 

Truck Tour | HackerRank

Solve the truck tour problem.

www.hackerrank.com

 

풀이

function truckTour(petrolpumps) {
    let petrol = 0;
    let pump = 0;

    for(let i = 0; i < petrolpumps.length; i++) {
        petrol += petrolpumps[i][0];
        petrol -= petrolpumps[i][1];
        if(petrol < 0) {
            petrol = 0;
            pump = i + 1;
        }
    }
    return pump;
}

1. 펌프인덱스와 기름양을 0으로 설정해줌

2. for문을 돌며, 각 펌프에서 기름을 더해 채워주고, 이동 거리 사용량을 빼줌

3. 만약 이동 거리가 더 길어서 기름이 똑 떨어지면, 기름을 0으로 다시 설정하고, 다음 펌프로 이동함(즉, 새로운 위치에서 새롭게 스타트)

4. 펌프값을 리턴함

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함