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

AAAABBBEEFFGG 3

A—A—A—A

AB–AB–AB–A   (加入B)

ABE-ABE-AB–A   (加入E)

ABEFABE-ABF-A   (加入F，每次尽可能填满或者是均匀填充)

ABEFABEGABFGA   (加入G)

ACCCEEE 2

CE-CE-CE

CEACE-CE   (加入A)

AAAABBBEEFFGG 3

A出现了4次，最多，mx=4，那么可以分为mx-1=3块，如下：

A—A—A—

ABEFABEGABFGA

ACCCEEE 2

C和E都出现了3次，最多，mx=3，那么可以分为mx-1=2块，如下：

CE-CE-

CEACE-CE

AAABBB 0

A和B都出现了3次，最多，mx=3，那么可以分为mx-1=2块，如下：

ABAB

``````class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> cnt(26, 0);
}
sort(cnt.begin(), cnt.end());
int i = 25, mx = cnt[25], len = tasks.size();
while (i >= 0 && cnt[i] == mx) --i;
return max(len, (mx - 1) * (n + 1) + 25 - i);
}
};
``````

``````class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int mx = 0, mxCnt = 0;
vector<int> cnt(26, 0);
if (mx == cnt[task - 'A']) {
++mxCnt;
} else if (mx < cnt[task - 'A']) {
mxCnt = 1;
}
}
int partCnt = mx - 1;
int partLen = n - (mxCnt - 1);
int emptySlots = partCnt * partLen;
int idles = max(0, emptySlots - taskLeft);
}
};
``````

``````class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int res = 0, cycle = n + 1;
unordered_map<char, int> m;
priority_queue<int> q;
for (char c : tasks) ++m[c];
for (auto a : m) q.push(a.second);
while (!q.empty()) {
int cnt = 0;
vector<int> t;
for (int i = 0; i < cycle; ++i) {
if (!q.empty()) {
t.push_back(q.top()); q.pop();
++cnt;
}
}
for (int d : t) {
if (--d > 0) q.push(d);
}
res += q.empty() ? cnt : cycle;
}
return res;
}
};
``````

Rearrange String k Distance Apart

Reorganize String