# 621.Task-Scheduler

## 621. Task Scheduler

## 题目地址

<https://leetcode.com/problems/task-scheduler/>

## 题目描述

```
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:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Constraints:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
```

## 代码

### Approach #1

```java
// (c[25] - 1) * (n + 1) + 25 - i  is frame size
// when inserting chars, the frame might be "burst", then tasks.length takes precedence
// when 25 - i > n, the frame is already full at construction, the following is still valid.
public class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] count = new int[26];
        for (char t: tasks){
            count[t - 'A']++;
        }
        Arrays.sort(count);

        int i = 25;
        while(i >= 0 && count[i] == count[25])     i--;
                // AB--AB--AB, 25 -i 为最后一个AB长度
        return Math.max(tasks.length, (count[25] - 1) * (n + 1) + 25 - i);
      // 每块有n+1个
    }
}
```

### Approach #2 Sorting

```java
class Solution {
  public int leastInterval(char[] tasks, int n) {
        int[] map = new int[26];
    for (char c: tasks) {
      map[c - 'A']++;
    }
    Arrays.sort(map); // sort
    int time = 0;
    while (map[25] > 0) {
      int i  = 0;
      while (i <= n) {
        if (map[25] == 0) break;
        if (i < 26 && map[25 - i] > 0) {
          map[25 - i]--;
        }
        time++;
        i++;
      }
      Arrays.sort(map);
    }
    return time;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/array/621.task-scheduler.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
