[JAVA 문제 풀이] 408. 과제 진행하기

프로그래머스 (176962)
Stupefyee's avatar
Jul 31, 2025
[JAVA 문제 풀이] 408. 과제 진행하기
notion image
notion image
 

내가 작성한 코드

import java.util.*; class Solution { public String[] solution(String[][] plans) { List<Subject> list = new ArrayList<>(); // 시작 시간을 분 단위로 변환하고 정렬하기 위한 리스트 List<String> answer = new ArrayList<>(); for (String[] plan : plans) { String name = plan[0]; String[] timeSplit = plan[1].split(":"); int hour = Integer.parseInt(timeSplit[0]); int minute = Integer.parseInt(timeSplit[1]); int startTime = hour * 60 + minute; // 시간을 분 단위로 변환 int playtime = Integer.parseInt(plan[2]); list.add(new Subject(name, startTime, playtime)); } // 시작 시간 기준으로 정렬 Collections.sort(list, (a, b) -> a.startTime - b.startTime); Stack<Subject> stack = new Stack<>(); // 멈춘 과제를 보관하는 스택 for (int i = 0; i < list.size(); i++) { Subject current = list.get(i); // 다음 과제 시작 시간 int nextStart = (i + 1 < list.size()) ? list.get(i + 1).startTime : Integer.MAX_VALUE; int endTime = current.startTime + current.duration; if (endTime <= nextStart) { // 현재 과제가 다음 과제 시작 전 끝나는 경우 answer.add(current.name); int remainingTime = nextStart - endTime; // 멈춰둔 과제 이어서 진행 while (!stack.isEmpty() && remainingTime > 0) { Subject paused = stack.pop(); if (paused.duration <= remainingTime) { // 멈춘 과제를 전부 끝낼 수 있는 경우 answer.add(paused.name); remainingTime -= paused.duration; } else { // 멈춘 과제를 끝내지 못하는 경우 다시 넣고 시간만 줄임 paused.duration -= remainingTime; stack.push(paused); break; } } } else { // 과제를 다 끝내지 못하고 중간에 멈춰야 하는 경우 current.duration -= nextStart - current.startTime; stack.push(current); } } // 남은 멈춰둔 과제들 처리 while (!stack.isEmpty()) { answer.add(stack.pop().name); } return answer.toArray(new String[0]); } // 과제 정보를 담는 클래스 static class Subject { String name; int startTime; int duration; Subject(String name, int startTime, int duration) { this.name = name; this.startTime = startTime; this.duration = duration; } } }
Share article

stupefyee