알고리즘/프로그래머스

[프로그래머스] 2022 KAKAO BLIND RECRUITMENT > 3. 주차 요금 계산

재담 2022. 2. 13. 20:45

문제 원본 : 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) {
        int[] answer = {};

        List<String> list = Arrays.asList(records);

        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.substring(6, 10).compareTo(o2.substring(6, 10));
            }
        });

        ArrayList<Integer> ans = new ArrayList<>();
        int parkingTime = 0;
        for (int i = 1; i < list.size(); ++i) {
            String preRecord = list.get(i - 1);
            String record = list.get(i);
            String[] preSpl = preRecord.split(" ");
            String[] spl = record.split(" ");

            if (preSpl[1].equals(spl[1])) {
                if (spl[2].equals("OUT")) {
                    int t1 = Integer.parseInt(preSpl[0].substring(0, 2)) * 60 + Integer.parseInt(preSpl[0].substring(3, 5));
                    int t2 = Integer.parseInt(spl[0].substring(0, 2)) * 60 + Integer.parseInt(spl[0].substring(3, 5));
                    parkingTime += (t2 - t1);
                }
            } else {
                if (preSpl[2].equals("IN")) {
                    int t1 = Integer.parseInt(preSpl[0].substring(0, 2)) * 60 + Integer.parseInt(preSpl[0].substring(3, 5));
                    int t2 = 23 * 60 + 59;
                    parkingTime += (t2 - t1);
                }

                if (parkingTime <= fees[0]) {
                    ans.add(fees[1]);
                } else {
                    ans.add(fees[1] + (int) Math.ceil((parkingTime - fees[0]) / (double) fees[2]) * fees[3]);
                }

                parkingTime = 0;
            }
        }

        if (list.get(list.size() - 1).split(" ")[2].equals("IN")) {
            int t1 = Integer.parseInt(list.get(list.size() - 1).split(" ")[0].substring(0, 2)) * 60 + Integer.parseInt(list.get(list.size() - 1).split(" ")[0].substring(3, 5));
            int t2 = 23 * 60 + 59;
            parkingTime += (t2 - t1);
        }

        if (parkingTime <= fees[0]) {
            ans.add(fees[1]);
        } else {
            ans.add(fees[1] + (int) Math.ceil((parkingTime - fees[0]) / (double) fees[2]) * fees[3]);
        }

        answer = new int[ans.size()];
        for (int i = 0; i < ans.size(); ++i) {
            answer[i] = ans.get(i);
        }

        return answer;
    }
}
  • 2022 카카오 블라인드 코딩 테스트 3번
  • records 배열을 차량번호로 정렬 후 주차요금 계산
  • Collections.sort 는 stable 하다.