[JAVA 문제 풀이] 345. 주차 요금 계산

프로그래머스 (92341)
Stupefyee's avatar
Jun 26, 2025
[JAVA 문제 풀이] 345. 주차 요금 계산
notion image
notion image

내가 작성한 코드

import java.util.*; class Solution { public int[] solution(int[] fees, String[] records) { // 기본 요금 정보 int basicTime = fees[0]; // 기본 시간 int basicFee = fees[1]; // 기본 요금 int unitTime = fees[2]; // 단위 시간 int unitFee = fees[3]; // 단위 요금 // 차량 번호별 입차 시각 저장 Map<String, Integer> inTimeMap = new HashMap<>(); // 차량 번호별 누적 주차 시간 저장 Map<String, Integer> totalTimeMap = new HashMap<>(); for (String record : records) { String[] parts = record.split(" "); String time = parts[0]; // 입차 or 출차시간 String carNum = parts[1]; // 차량 번호 String type = parts[2]; // 입차 or 출차 int minutes = toMinutes(time); // 입차 시각 저장 if (type.equals("IN")) { inTimeMap.put(carNum, minutes); } else { // 출차 시 입차 시각 가져와서 주차 시간 계산 int inTime = inTimeMap.remove(carNum); // 입차 시각 제거 int parkedTime = minutes - inTime; totalTimeMap.put(carNum, totalTimeMap.getOrDefault(carNum, 0) + parkedTime); } } // 출차 기록 없는 차량은 23:59에 출차한 것으로 간주 int endOfDay = toMinutes("23:59"); for (String carNum : inTimeMap.keySet()) { int inTime = inTimeMap.get(carNum); int parkedTime = endOfDay - inTime; totalTimeMap.put(carNum, totalTimeMap.getOrDefault(carNum, 0) + parkedTime); } // 차량 번호 순으로 정렬하여 요금 계산 List<String> carList = new ArrayList<>(totalTimeMap.keySet()); Collections.sort(carList); int[] answer = new int[carList.size()]; for (int i = 0; i < carList.size(); i++) { String carNum = carList.get(i); int totalTime = totalTimeMap.get(carNum); answer[i] = calculateFee(totalTime, basicTime, basicFee, unitTime, unitFee); } return answer; } // "HH:MM" → 분으로 변환 private int toMinutes(String time) { String[] split = time.split(":"); return Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]); } // 요금 계산 private int calculateFee(int time, int basicTime, int basicFee, int unitTime, int unitFee) { if (time <= basicTime) { return basicFee; } else { return basicFee + (int) Math.ceil((time - basicTime) / (double) unitTime) * unitFee; } } }
Share article

stupefyee