[Leedcode]621.Task Scheduler

149 阅读2分钟

Descriptiion:
You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.

Return the minimum number of intervals required to complete all tasks.

Input:  tasks = ["A","A","A","B","B","B"], n = 2
Output:  8
Explanation:  A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.

After completing task A, you must wait two cycles before doing A again.
The same applies to task B. In the 3rd interval, neither A nor B can be done, 
so you idle. By the 4th cycle, you can do A again as 2 intervals have passed.

Solution: Optimized Task Scheduling with Cooling Time Constraint: A Greedy Approach

1.Count the frequency of each task using an array;
2.Sort the frequencies;
3.Calculate the number of intervals needed base on the task4. with the maximum frequency, considering the booling time constraint.
4.Return the total number of intervals required.

Using the maximum frequency to calculate the minimum intervals. Let's consider such situation: AAAAAA BBBBBB CCCCC DD n=4:

First, A is the maximum frequency Char, to arrange A, the work flow , at least like this, A _ _ _ _ A _ _ _ _ A _ _ _ _ A _ _ _ _ A _ _ _ _ A. So we have (6-1) * 4 = 20 sites for other chars. Because A is the maximum frequency Char, the frequencies of other chars are less than or equal to A, if equal to A, add the chars to the end of the last A, A _ _ _ _ A _ _ _ _ A _ _ _ _ A _ _ _ _ A _ _ _ _ ABCDEFGHIJK, and they will never mismarch the intervals.

Next, filling the chunks between A.

  • the frequency of B is 6, so B can fill min(chunk, B freq) = min (5, 6) = 5 places. A B _ _ _ A B _ _ _ A B _ _ _ A B _ _ _ A B _ _ _ AB.
  • the frequency of C is 5, so C can fill min(5, 5) = 5 places. A B C _ _ A B C _ _ A B C _ _ A B C _ _ A B C _ _ AB.
  • the frequency of D is 2, so D can fill min(5, 2) = 2 places.A B C D _ A B C D _ A B C _ _ A B C _ _ A B C _ _ AB.

Finally, we can calculate the minimum intervals = {20 (sites) - 5(B occupied) - 5(C occupied) - 2(D occupied)}(empty sites) + 19(the chars of tasks) = 27.

fun leastInterval(tasks: CharArray, n: Int): Int {
    val chars = IntArray(26)
    tasks.forEach {
        chars[it - 'A']++
    }
    chars.sortDescending()
    // maximum numbers of intervals of chars
    val chunk = chars[0] - 1
    // maximum numbers of sites
    var idle = chunk * n

    for(i in 1 until chars.size) {
        // the occupied sites of each char
        idle -= min(chunk, chars[i])
    }
    
    // if idle <0 means more chars than the sites, for example, ABCDABCEHIJKA n=2
    return if (idle <=0) tasks.size else tasks.size + idle
}