[알고리즘/C#] 프로그래머스 - 호텔 대실 (Lv.2)

0시0분·2024년 8월 16일
0

알고리즘

목록 보기
19/23

🎈 풀이 과정
예전에 풀었던 과제 진행하기와 비슷한 문제다.
대신 중단되는 경우 없이 방을 늘리면 돼서 비교적 쉽게 풀었다.
고려해야하는 조건 역시 비슷하다.

  • 가장 빠른 퇴실 시간 == 다음 고객의 입실 시간 👉 그 방 그대로 사용
  • 가장 빠른 퇴실 시간 > 다음 고객의 입실 시간 👉 새 방 필요
  • 가장 빠른 퇴실 시간 < 다음 고객의 입실 시간 👉 언제든 입실 가능

🔧 놓쳤던 부분
처음 코드를 돌렸을때 21점이 나왔다. 로직엔 문제가 없는것 같아서 문제를 다시 읽었더니
10분의 청소시간을 고려하지 않아서.. 였다.
수정하고 재채점 했더니 이번엔 딱 두 문제가 틀렸다. 질문하기를 열심히 뒤져본 결과,
퇴실시간에 청소시간 10분을 더해서 계산했는데 이때 분의 단위가 60을 넘으면
시간으로 처리해야 하는 부분을 놓쳤었다.

using System;
using System.Collections.Generic;

public class Solution {
	// 📕 어차피 24시간 표기이므로 분으로 변환하지 않고 시간을 그대로 사용했다.
    private int ConvertTimeStringToInt(string str, bool isCheckOut)
    {
        string[] strs = str.Split(':');

        int hour = int.Parse(strs[0]);
        // 📕 청소시간을 퇴실시간에 포함
        int minute = int.Parse(strs[1]) + (isCheckOut ? 10 : 0);	
		// 📕 분단위가 60을 넘을 경우 시간으로 처리
        if (minute >= 60)
        {
            minute -= 60;
            hour++;
        }
        return hour * 100 + minute;
    }
	
    // 📕 가장 빠른 퇴실 방
    private int GetSoonCheckOut(List<(int, int)> checkIns)
    {
        int idx = 0;

        for (int i = 1; i < checkIns.Count; ++i)
        {
            if (checkIns[idx].Item2 > checkIns[i].Item2)
                idx = i;
        }

        return idx;
    }

    public int solution(string[,] book_time)
    {
        List<(int, int)> bookTimeList = new List<(int, int)>();
        for (int i = 0; i < book_time.GetLength(0); ++i)
            bookTimeList.Add((ConvertTimeStringToInt(book_time[i, 0], false), ConvertTimeStringToInt(book_time[i, 1], true)));
       	// 📕 입실시간 빠른 순으로 정렬
        bookTimeList.Sort();


        List<(int, int)> checkInRoom = new List<(int, int)>();
        checkInRoom.Add(bookTimeList[0]);
        int needRoomCnt = 1;

        for (int i = 1; i < bookTimeList.Count; ++i)
        {
            // 현재 가장 빠른 퇴실 방보다 입실 시간이 빠름
            // => 방 추가로 필요
            if (bookTimeList[i].Item1 < checkInRoom[GetSoonCheckOut(checkInRoom)].Item2)
            {
                checkInRoom.Add(bookTimeList[i]);
                needRoomCnt++;
            }
            // 현재 가장 빠른 퇴실 시간이랑 입실 시간이 같음
            else if (bookTimeList[i].Item1 == checkInRoom[GetSoonCheckOut(checkInRoom)].Item2)
            {
                checkInRoom[GetSoonCheckOut(checkInRoom)] = bookTimeList[i];
            }
            // 가장 빠른 퇴실이 다음 입실보다 빠를 때
            else
            {
                checkInRoom[GetSoonCheckOut(checkInRoom)] = bookTimeList[i];
				// 📕 나머지 방도 체크해야 함
                while (checkInRoom[GetSoonCheckOut(checkInRoom)].Item2 < bookTimeList[i].Item1)
                {
                    // 📕 언제든 입실 가능하도록 입실 시간으로 초기화
                    checkInRoom[GetSoonCheckOut(checkInRoom)] = (bookTimeList[i].Item1, bookTimeList[i].Item1);	
                }
            }
        }

        return needRoomCnt;
    }
}

0개의 댓글