https://school.programmers.co.kr/learn/courses/30/lessons/92341
로직
record를 돌며 차량 마다 총 소비한 시간을 계산한다
분 단위로 계산하기 위해 (시간* 60+분)으로 계산해준다
IN들어갈때는 위에 계산한 시간을 뺴주고
OUT나갈떄는 더해준다
records 순환을 끝내고 시간이 <= 0인 차량은 아직 안 나온 차량이므로 23:59 시간을 더해준다
챠량마다 총 소비한 돈을 정리한다
기본시간보다 적거나 같으면 기본요금만 내고, 기본시간보다 크면 기본시간 + ((총 시간 - 기본시간) / 단위 ) * 단위당 요금
단위로 안 나눠질땐 올림한다
차량번호 별로 sort한뒤 각 요금을 리턴한다.
전체코드
function solution(fees, records) {
var answer = [];
const [defaultTime, defaultCost, unit, unitCost] = fees;
const parkingTime = {};
for (const record of records) {
const [t, id, type] = record.split(' ');
const [h, m] = t.split(':');
const time = Number(h) * 60 + Number(m);
if (!parkingTime[id]) parkingTime[id] = 0;
// 들어가면-, 나오면 +
if (type === 'IN') {
parkingTime[id] -= time;
} else if (type === 'OUT') {
parkingTime[id] += time;
}
}
// 0보다 작은 시간 = 아직 출차하지 않은 차는 23:59에 출차한다
for (const [id, time] of Object.entries(parkingTime)) {
if (time <= 0) {
parkingTime[id] += 1439; // 23*60+59
}
}
// 비용계산
Object.entries(parkingTime).forEach(([id, time]) => {
let cost = 0;
if (time < defaultTime) {
cost = defaultCost;
} else {
cost = defaultCost + Math.ceil((time - defaultTime)/unit)*unitCost;
}
answer.push([Number(id), cost]);
})
answer.sort((a, b) => a[0] - b[0]);
return answer.map(a => a[1]);
}
'알고리즘' 카테고리의 다른 글
[DP] 정수 삼각형 (0) | 2023.08.31 |
---|---|
[DP] 가장 큰 정사각형 찾기 (0) | 2023.08.31 |
[프로그래머스 카카오블라인드] 문자열 압축 (0) | 2023.08.30 |
[프로그래머스 LV2] 리코쳇 로봇 (bfs) (0) | 2023.08.29 |
[프로그래머스LV2] 미로찾기 (bfs) (0) | 2023.08.29 |