코딩테스트 풀이

프로그래머스 코딩테스트 - 과제 진행하기

hanlabong 2024. 11. 6. 22:26
728x90

문제 설명

제한사항

 

해결방법

아이디어

  1. 과제 시작시간 순으로 정렬
  2. 처음 부여받은 과제를 모두 시작할 때까지 반복
    1. 지금 진행중인 과제와 새로 시작해야 할 과제 시간 텀 구하기
    2. 진행중인 과제가 끝나지 않았다면
      1. 남은 과제 스택에 삽입
    3. 진행중인 과제가 끝났다면
      1. 현제 과제를 answer에 삽입
      2. 남은 과제 스택에서 남은 과제를 꺼내면서 남은 시간만큼 진행할 수 있는 과제 진행
    4. 다음 과제 진행

코드

function solution(plans) {
    var answer = [];
    const stack = [];
    plans.sort((a, b) => a[1] < b[1] ? -1 : 1);
    let now = plans.shift();
    
    while(plans.length) {
        const next = plans.shift();
        const nowT = parseInt(now[2]);
        const [nowH, nowM] = now[1].split(":");
        const [nextH, nextM] = next[1].split(":");
        
        let left = (parseInt(nextH) - parseInt(nowH)) * 60 + (parseInt(nextM) - parseInt(nowM));
        
        if (nowT > left) {
            stack.push([now[0], nowT - left]);
        } else {
            answer.push(now[0]);
            left -= nowT;
            while (stack.length) {
                const [leftN, leftT] = stack.pop();
                if (left < leftT) {
                    stack.push([leftN, leftT - left]);
                    break;
                }
                answer.push(leftN);
                left -= leftT;
            }
        }
        now = next
    }
    answer.push(now[0])
    return answer.concat(stack.reverse().map((s) => s[0]));
}

결과

성공🌟

728x90