본문 바로가기

Leetcode 100문제 도전

[Leetcode 31/100] Task Scheduler - Medium

leetcode.com/problems/task-scheduler/

 

Task Scheduler - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 풀이 방식

Greedy 풀이

주의할 점

이 문제는 가장 많은 task의 count가 idle의 값을 결정할 수 있다는 것을 깨닫는 것이 중요하다.

노트로 최대한 많은 케이스의 문제를 예시로 직접 작성해보면서 규칙을 찾아서 풀려고 노력했다.

소스코드

class Solution {
    public int leastInterval(char[] tasks, int n) {
        if(n == 0) return tasks.length;

        int[] taskCount = new int[26];
        
        for(char task : tasks){
            taskCount[task - 'A']++;
        }
        
        int max = 0;
        int count = 1;
        
        for(int num : taskCount){
            if(num == 0) continue;
            
            if(max < num){
                max = num;
                count = 1;
            } else if(max == num){
                count++;
            }
        }
        int res = (n+1)*(max-1)+count;
        return res >= tasks.length ? res : tasks.length;
    }
}