본문 바로가기

프로그래머스/Level 2

프로그래머스 - 과제 진행하기(Python)

 알고리즘을 나눈다면 구현 알고리즘일 것 같다.

 

문제를 그대로 구현해 주면 되는 문제이지만, 약간의 팁(?)이라면 걸리는 시간 하고, 시작 시간이 문자열로 되어 있어 귀찮으니 전부 int로 바꿔주자

 

12:40은 12*60+40 = 760으로 어차피 00:00에서 760분이 지난 시점이기 때문에 다른 것들도 동일하게 바꿔준다면 우리가 아는 시간 체계와 다를 게 없다. 또 스케줄이기 때문에 시간을 기준으로 오름차순을 해주면 편하겠지?

<문제>

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 


<소스코드>

 

def solution(plans):
    answer = []
    stack = []

    # 시간 정수로 변환
    for plan in plans:
        h, m = map(int, plan[1].split(":"))
        plan[1] = h * 60 + m
        plan[2] = int(plan[2])

    plans.sort(key=lambda x: x[1])  # 시작 시간 기준 정렬

    for i in range(len(plans) - 1):
        name, start, duration = plans[i]
        next_start = plans[i + 1][1]
        interval = next_start - start

        if interval >= duration:
            answer.append(name)
            remain_time = interval - duration
            # stack에서 꺼내서 처리
            while stack and remain_time > 0: #스택이 비어있지 않은 한 그리고 남은 시간이 존재하는 한
                s_name, s_time = stack.pop()
                if remain_time >= s_time:
                    answer.append(s_name)
                    remain_time -= s_time
                else:
                    stack.append((s_name, s_time - remain_time))
                    break
        else:
            # 다 못 한 건 stack에 저장
            stack.append((name, duration - interval))

    # 마지막 과제는 무조건 끝냄
    answer.append(plans[-1][0])

    # stack 남은 거 처리
    while stack:
        answer.append(stack.pop()[0])

    return answer