@TOC

## # 题目描述

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].

## # 解题方法

### # 公式法

1. 如给定：AAABBCD，n=2。那么我们满足个数最多的任务所需的数量，即可以满足任务间隔要求，即：AXXAXXA；（其中，X表示需要填充任务或者idle的间隔）
2. 如果有两种或两种以上的任务具有相同的最多的任务数，如：AAAABBBBCCDE，n=3。那么我们将具有相同个数的任务A和B视为一个任务对，最终满足要求的分配为：ABXXABXXABXXAB，剩余的任务在不违背要求间隔的情况下穿插进间隔位置即可，空缺位置补idle。
3. 由上面的分析我们可以得到最终需要最少的任务时间：（最多任务数-1）*（n + 1） + （相同最多任务的任务个数）

``````class Solution(object):
"""
:type n: int
:rtype: int
"""
most = count.most_common()[0][1]
num_most = len([i for i, v in count.items() if v == most])
time = (most - 1) * (n + 1) + num_most
``````

``````class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
map<char, int> counter;
int most_common = 0;
for (auto t : counter)
most_common = max(most_common, t.second);
int count_most = 0;
for (auto t : counter)
if (t.second == most_common)
count_most ++;
int res = (n + 1) * (most_common - 1) + count_most;