[프로그래머스(Programmers)][자바(java)] (Lv2) 주차 요금 계산 <2022 KAKAO BLIND RECRUITMENT>

728x90

 

https://programmers.co.kr/learn/courses/30/lessons/92341

 

코딩테스트 연습 - 주차 요금 계산

[180, 5000, 10, 600] ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] [14600, 34400, 5000]

programmers.co.kr

 

문제 풀이

 

import java.util.*;

public class Solution {

	public int[] solution(int[] fees, String[] records) {
		StringTokenizer st, time; int num;
		Map<Integer, Deque<Integer>> map_minutes = new TreeMap<>();
		for (String record : records) {
			st = new StringTokenizer(record);
			time = new StringTokenizer(st.nextToken(), ":");
			num = Integer.parseInt(st.nextToken());
			if (!map_minutes.containsKey(num))
				map_minutes.put(num, new ArrayDeque<>());
			map_minutes.get(num).add(Integer.parseInt(time.nextToken()) * 60 
									+ Integer.parseInt(time.nextToken()));
		}
		int cnt = map_minutes.size(), answer[] = new int[cnt], i = 0, 
			time_in, time_out, time_total, fee_total;
		int time_base = fees[0], fee_base = fees[1], 
			time_unit = fees[2], fee_unit = fees[3];
		for (Deque<Integer> queue : map_minutes.values()) {
			time_total = 0;
			while (!queue.isEmpty()) {
				time_in = queue.poll();
				time_out = queue.isEmpty() ? 1439 : queue.poll(); // 1439 = 23:59
				time_total += time_out - time_in;
			}
			fee_total = fee_base;
			if (time_total > time_base)
				fee_total += ((int) Math.ceil((double) (time_total - time_base) 
														/ time_unit) * fee_unit);
			answer[i++] = fee_total;
		}
		return answer;
	}
}

 

전달받은 String[] records 의 기록들은 시간 순으로 되어 있기 때문에
   차량 번호 별 시간 기록을 차례로 넣으면 IN - OUT [ - IN - OUT ... ] 순서로 있을 것이다
 ( 입차 된 후 출차 기록이 없다면 ( = 시간 기록 개수가 홀수이면 ) 가장 마지막 출차 시간은 23:59 )

TreeMap map_minutes 생성  ( key 기준 오름차순 )
 ( 차량 번호를 key 로 하고, 입차/출차 시각( 분 단위 ) 들을 담은 큐를 value 로 함 )

map_minutes 의 values ( Queue ) 들을 순회하며
   주차 시간( 출차 시각 - 입차 시각 ) 의 총합( time_total )을 구한 후, 지불할 금액( fee_total )을 구함

-  총 요금  ☞  기본 요금 + ( 주차 시간 - 기본 시간 ) /  단위 시간 * 단위 요금
 ( 이 때, 주차 시간이 기본 시간보다 적은 경우 기본 요금만 지불 )
 ( fee_total ) ( fee_base ) ( time_total ) ( time_base ) ( time_unit ) ( fee_unit )
  

반응형