알고리즘

프로그래머스 주차 요금 계산 (JAVA)

박카스마시며코딩 2023. 8. 7. 14:00

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

 

프로그래머스

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

programmers.co.kr

 

저는 구현을 통해 문제를 해결하였습니다.

Map을 통해 각각의 차량의 주차한 시간을 구하였고, 다른 Map을 통해 들어온 시간을 체크하였습니다. 이를 통해 들어오고 나가지 않은 것은 마지막에 23:59에 나간것으로 체크하도록 구현하였고, 각각의 주차시간을 통해 요금을 구하여 문제를 해결하였습니다.

 

import java.util.*;

class Solution {
    private static final int LAST_TIME = changeStringToMin("23:59");
    public int[] solution(int[] fees, String[] records) {
        int[] answer = {};
        Map<Integer,Integer> carTime = new HashMap<>();
        Map<Integer,Integer> carInTime = new HashMap<>();
        for(String record : records){
            String[] str = record.split(" ");
            int min = changeStringToMin(str[0]);
            int carNum = Integer.parseInt(str[1]);
            if(str[2].equals("IN")){
                carInTime.put(carNum,min);
            }else{
                int prevMin = carInTime.get(carNum);
                int time = min - prevMin;
                carTime.merge(carNum,time,(v1,v2)->{
                    return v1 + time;
                });
                carInTime.remove(carNum);
            }
        }
        for(int carNum : carInTime.keySet()){
            int prevMin = carInTime.get(carNum);
            int time = LAST_TIME - prevMin;
            carTime.merge(carNum,time,(v1,v2)->{
                    return v1 + time;
            });
            
        }
        PriorityQueue<int[]> pq = new PriorityQueue<>((v1,v2)->{
            return v1[0] - v2[0];
        });
        for(int carNum : carTime.keySet()){
            int fee = calFee(carTime.get(carNum),fees);
            pq.offer(new int[]{carNum,fee});
        }
        answer = new int[pq.size()];
        for(int i = 0 ; i < answer.length ; i++){
            answer[i] = pq.poll()[1];
        }
        return answer;
    }
    private static int calFee(int time , int[] fees){
        if(time <= fees[0]){
            return fees[1];
        }
        int temp = time - fees[0];
        if(temp % fees[2] != 0){
            temp /= fees[2];    
            temp++;
        }else{
            temp /= fees[2];  
        }
        return fees[1] + temp * fees[3];
    }
    private static int changeStringToMin(String s){
        String[] str = s.split(":");
        int result = Integer.parseInt(str[0]) * 60 + Integer.parseInt(str[1]);
        return result;
    }
}