본문 바로가기
Beakjoon&프로그래머스/Java

[프로그래머스/Java] 주차 요금 계산

by 현장 2026. 4. 2.

-Code

import java.util.*;

class Solution {
    static class FeeInfo {
        String carNum;
        int fee;

        public FeeInfo(String carNum, int fee) {
            this.carNum = carNum;
            this.fee = fee;
        }
    }
    static int endTime = 23 * 60 + 59;
    
    public int[] solution(int[] fees, String[] records) {
        // 들어온 시간 계산을 위한 맵
        Map<String, Integer> inTimeMap = new HashMap<>();
        // 총 결재 금액 계산을 위한 맵
        Map<String, Integer> totalTimeMap = new HashMap<>();
        for (String record : records) {
            StringTokenizer st = new StringTokenizer(record);
            // 시간을 분으로 변경
            String[] timeStr = st.nextToken().split(":");
            int nowTime = Integer.parseInt(timeStr[0]) * 60 +
                    Integer.parseInt(timeStr[1]);
            String carNum = st.nextToken();
            String comm = st.nextToken();
            // 출차와 입차의 경우 확인
            if (comm.equals("IN")) {
                // 입차의 경우 시간 저장
                inTimeMap.put(carNum, nowTime);
            } else {
                // 출차의 경우 주차장에 있는 시간 저장
                int inTime = inTimeMap.get(carNum);
                int beforeTime = totalTimeMap.getOrDefault(carNum, 0);
                int sumTime = (nowTime - inTime) + beforeTime;
                totalTimeMap.put(carNum, sumTime);
                inTimeMap.remove(carNum);
            }
        }
        // 아직 주차장에 차가 있는 경우 23:59분을 기준으로 계산
        for (String carNum : inTimeMap.keySet()) {
            int inTime = inTimeMap.get(carNum);
            int beforeTime = totalTimeMap.getOrDefault(carNum, 0);
            int sumTime = (endTime - inTime) + beforeTime;
            totalTimeMap.put(carNum, sumTime);
        }
        // 시간에 따른 결재 비용 계산
        FeeInfo[] feeInfos = new FeeInfo[totalTimeMap.size()];
        int idx = 0;
        for (String carNum : totalTimeMap.keySet()) {
            // 기본 요금
            int nowFee = fees[1];
            // 기본 시간 보다 클경우 비용 추가
            if (totalTimeMap.get(carNum) > fees[0]) {
                // 올림 처리
                double calcTime = ((double) totalTimeMap.get(carNum) - fees[0]) / fees[2];
                nowFee += (int) Math.ceil(calcTime) * fees[3];
            }
            feeInfos[idx++] = new FeeInfo(carNum, nowFee);
        }
        // 차 번호 순서에 따라 정렬
        Arrays.sort(feeInfos, (o1, o2) -> {
            return o1.carNum.compareTo(o2.carNum);
        });
        // 결과 변환
        int[] answer = new int[totalTimeMap.size()];
        for (int i = 0; i < totalTimeMap.size(); i++) {
            answer[i] = feeInfos[i].fee;
        }
        return answer;
    }
}

class를 만들어 정렬한 부분이 불필요한 것 같다고 생각이 들긴하지만 직관적 보이는 장점이 있어 생성해서 정렬했습니다.