Algorithm/코테 연습

[프로그래머스 코테 연습]자바 - 주차 요금 계산

나맘임 2024. 7. 8. 02:53

개요

코딩테스트 연습 - 주차 요금 계산 | 프로그래머스 스쿨 (programmers.co.kr)

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

난이도 : 레벨 2

특징 : 2018 KAKAO BLIND RECRUITMENT 기출 문제

 

문제만 잘 읽고 하면 되는 문제입니다..

 

처음 이 문제를 접근했을 땐, 차량이 OUT 될 때마다 요금을 계산하면 됐었는데 

 

생각해보니 시간만 계산하고 나중에 정산을 하면 되더라고여..

 

뻘짓을 많이 한 문제였습니다.

 

풀이법

import java.util.*;

class Solution {
        public static int[] solution(int[] fees, String[] records) {
        int defaultTime = fees[0];
        int defaultFee = fees[1];
        int unitTime = fees[2];
        int unitFee = fees[3];

        HashMap<Integer, Integer> parkingLotStatus = new HashMap<>(); //자동차 번호, 입차 시간
        TreeMap<Integer, Integer> carTimes = new TreeMap<>();

        for (int i = 0; i < records.length; i++){
            String[] splitRecord = records[i].split(" ");
            int time = getMin(splitRecord[0]);
            int carNumber = Integer.parseInt(splitRecord[1]);
            String action = splitRecord[2];

            if (action.equals("IN")){
                parkingLotStatus.put(carNumber,time);
            } else{
                int carStayTime = time - parkingLotStatus.remove(carNumber);
                carTimes.put(carNumber, carTimes.getOrDefault(carNumber, 0) +carStayTime);
            }
        }

        for (Map.Entry<Integer, Integer> entry : parkingLotStatus.entrySet()) {
            int carNumber = entry.getKey();
            int inTime = entry.getValue();
            int carStayTime = 1439 - inTime; // 1439는 23:59를 분으로 환산한 값
            carTimes.put(carNumber, carTimes.getOrDefault(carNumber, 0) + carStayTime);
        }

        int[] answer = new int[carTimes.size()];
        int index = 0;
        for (Map.Entry<Integer, Integer> entry : carTimes.entrySet()) {
            int totalTime = entry.getValue();
            int resultFee = defaultFee;
            if (totalTime > defaultTime) {
                resultFee += Math.ceil((totalTime - defaultTime) / (double) unitTime) * unitFee;
            }
            answer[index++] = resultFee;
        }

        return answer;
    }

    private static int getMin(String time){
        String[] splitTime = time.split(":");
        int hour = Integer.parseInt(splitTime[0]);
        int min = Integer.parseInt(splitTime[1]);
        return hour *60 + min;
    }
}

중요 포인트

1. 두 개의 Map을 사용한다. 차량의 입장과 퇴장을 관리할 HashMap과 정산 결과를 만들어낼 TreeMap이다. 여기서 TreeMap을 사용한 이유는 차량 번호 오름차순으로 정산한 값을 나열하여 배열을 만들어야하기 때문이다. Key 기준으로 오름차순 정렬이 되는 TreeMap을 사용하게 되면 이를 매우 쉽게 해결할 수 있다.

 

2. Integer.parseInt() 쓰면 String을 잘 int로 바꿔준다. (0000 -> 0 까지 가능하다)

 

3. Map의 getOrDefault 메소드를 사용하면 key가 없는 값에 대해서 기본값을 부여할 수 있다.

 

과정

1. 먼저, Records 배열을 돌면서 차량의 IN, OUT을 찾아 총 주차 시간을 계산하여 carTime 트리맵에 저장한다. 이 때, parkingLotStatus Map을 사용하여 입퇴장을 감지한다.

 

2. 퇴장하지 않은 자동차가 있을 수도 있으므로 parkLotStatus Map을 한번 더 순회하여 계산해준다. 23:59를 분으로 바꾸면 1439분이다.

 

3. 이제까지 진행했으면 carTime 트리맵엔 차량번호 오름차순대로 해당 차량이 주차한 총 시간을 가지게 된다. 반복문으로 순회하면서 최종 정산 비용을 계산한다.

 

4. 배열에 담는다.