> For the complete documentation index, see [llms.txt](https://twchen.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://twchen.gitbook.io/leetcode/array/task-scheduler.md).

# Task Scheduler

## Description

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval **n** that means between two **same tasks**, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the **least** number of intervals the CPU will take to finish all the given tasks.

**Example 1:**

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

**Note:**

1. The number of tasks is in the range \[1, 10000].
2. The integer n is in the range \[0, 100].

## Solutions

Credit: [concise Java Solution O(N) time O(26) space](https://leetcode.com/problems/task-scheduler/discuss/104496/concise-Java-Solution-O\(N\)-time-O\(26\)-space)

Idea:

Consider the example `AAABBBCCDDE` with `n = 3`

1. Construct a frame using the most frequent types of tasks. The frame consists of many blocks. Each block is a sequence of most frequent types of tasks. `ABxxABxxAB` for the example.
2. For each remaining type of tasks, add the tasks between the blocks. For the example,
   1. Add `C`: `ABCxABCxAB`
   2. Add `D`: `ABCDABCDAB`
   3. Add `E`: `ABCDEABCDAB`

```cpp
class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        if(tasks.empty()) return 0;
        vector<int> freqs(26);
        for(auto task : tasks)
            ++freqs[task - 'A'];
        sort(freqs.begin(), freqs.end(), greater<int>());
        int f = freqs[0], i = 1;
        while(i < 26 && freqs[i] == f) ++i;
        int frame_size = max(i, n + 1) * (f - 1) + i;
        int num = i * f;
        while(i < 26 && freqs[i] > 0){
            num += freqs[i];
            ++i;
        }
        return max(num, frame_size);
    }
};
```

The above solution can be simplified to:

```cpp
class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        if(tasks.empty()) return 0;
        vector<int> freqs(26);
        for(auto task : tasks)
            ++freqs[task - 'A'];
        sort(freqs.begin(), freqs.end(), greater<int>());
        int f = freqs[0], i = 1;
        while(i < 26 && freqs[i] == f) ++i;
        int frame_size = max(i, n + 1) * (f - 1) + i;
        int num = tasks.size();
        return max(num, frame_size);
    }
};
```

Because at the end `num == nums.size()`.
