[Java] 프로그래머스 과제 진행하기

hyunnzl·2025년 3월 23일

프로그래머스

목록 보기
15/58
post-thumbnail

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

난이도

Level 2

문제

과제를 받은 루는 다음과 같은 순서대로 과제를 하려고 계획을 세웠습니다.

  • 과제는 시작하기로 한 시각이 되면 시작합니다.
  • 새로운 과제를 시작할 시각이 되었을 때, 기존에 진행 중이던 과제가 있다면 진행 중이던 과제를 멈추고 새로운 과제를 시작합니다.
  • 진행중이던 과제를 끝냈을 때, 잠시 멈춘 과제가 있다면, 멈춰둔 과제를 이어서 진행합니다.
  • 만약, 과제를 끝낸 시각에 새로 시작해야 되는 과제와 잠시 멈춰둔 과제가 모두 있다면, 새로 시작해야 하는 과제부터 진행합니다.
  • 멈춰둔 과제가 여러 개일 경우, 가장 최근에 멈춘 과제부터 시작합니다.

과제 계획을 담은 이차원 문자열 배열 plans가 매개변수로 주어질 때, 과제를 끝낸 순서대로 이름을 배열에 담아 return 하는 solution 함수를 완성해주세요.

내 코드

import java.util.*;

class Solution {

    static class Plan {
        String name;
        int startTime;
        int duration;

        public Plan(String name, String start, String duration) {
            this.name = name;
            this.startTime = toMinute(start);
            this.duration = Integer.parseInt(duration);
        }

        private static int toMinute(String t) {
            String[] parts = t.split(":");
            return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]);
        }
    }

    public String[] solution(String[][] plans) {
        Plan[] planList = new Plan[plans.length];
        for (int i = 0; i < plans.length; i++) {
            planList[i] = new Plan(plans[i][0], plans[i][1], plans[i][2]);
        }

        Arrays.sort(planList, Comparator.comparingInt(p -> p.startTime));

        Stack<Plan> stack = new Stack<>();
        List<String> answerList = new ArrayList<>();
        int now = planList[0].startTime;

        for (int i = 0; i < planList.length; i++) {
            Plan cur = planList[i];

            now = Math.max(now, cur.startTime);

            int nextStart = (i < planList.length - 1) ? planList[i + 1].startTime : Integer.MAX_VALUE;
            int available = nextStart - now;

            if (cur.duration <= available) {
                now += cur.duration;
                answerList.add(cur.name);

                int remainTime = nextStart - now;
                while (!stack.isEmpty() && remainTime > 0) {
                    Plan paused = stack.pop();
                    if (paused.duration <= remainTime) {
                        now += paused.duration;
                        remainTime -= paused.duration;
                        answerList.add(paused.name);
                    } else {
                        paused.duration -= remainTime;
                        now = nextStart;
                        stack.push(paused);
                        break;
                    }
                }
            } else {
                cur.duration -= available;
                now = nextStart;
                stack.push(cur);
            }
        }

        while (!stack.isEmpty()) {
            answerList.add(stack.pop().name);
        }

        return answerList.toArray(new String[0]);
    }
}

0개의 댓글