티스토리 뷰
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. 펌프값을 리턴함
'1Day 1Algorithm' 카테고리의 다른 글
[DAY 29] 실패율 (2019 KAKAO BLIND RECRUITMENT) @ (0) | 2019.10.29 |
---|---|
[DAY 28] 문자열 내 p와 y의 개수 (0) | 2019.10.29 |
[DAY 26] Queue using Two Stacks (0) | 2019.10.26 |
[DAY 25] 비밀지도 (2018 KAKAO BLIND RECRUITMENT) (0) | 2019.10.26 |
[DAY 24] 약수의 합 (0) | 2019.10.25 |
- Total
- Today
- Yesterday
- OS
- Algorithm
- sort
- 컴퓨터공학
- 자료구조
- 배열
- 1day1algorithm
- 알고리즘
- sort()
- 운영체제
- 구간합
- 멀티프로그래밍
- js
- Typescript
- 타입스크립트
- 배치처리시스템
- Props
- Array
- Webpack
- 웹팩
- javascript
- React
- 시분할시스템
- 프로그래머스
- reduce()
- 우아한테크러닝
- 리액트
- 자바스크립트
- redux-saga
- greedyAlgorithm
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |