【
CPU to the list of tasks to be performed by a given character array representation. Which comprises using uppercase A - 26 different types of letters Z tasks. Task may be performed in any order, and each task may all be executed within a unit time. CPU can perform a task at any one time unit, or in standby.
However, it must have the same kind between the two tasks cooling time length n, so that at least n consecutive units of time within the CPU to perform different tasks, or the standby state.
You need to calculate the shortest time to complete all the tasks required.
Example 1:
Input: tasks = [ "A", "A", "A", "B", "B", "B"], n = 2
Output: 8
execution order: A -> B -> (standby) -> A -> B -> (standby) -> A -> B.
Note:
The total number of task is [1, 10000].
n is in the range [0, 100].
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/task-scheduler
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
】
This question is a bit different with the title did before, use the block thought.
First character hash statistics the most frequent character, the number is mxcnt, then divided into mxpart = mxcnt - 1 blocks.
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int leastInterval(char* tasks, int tasksSize, int n){
int cnt[26] = {0};
int i;
int partlen = n + 1; // 每一块最小长度
char temp;
int samemx = 0; // 最多出现次数的个数
int mxcnt = 0; // 最多出现次数
int ret;
for (i = 0; i < tasksSize; i++) {
temp = tasks[i] - 'A';
cnt[temp]++;
if (mxcnt < cnt[temp]) {
mxcnt = cnt[temp];
samemx = 1;
} else if (mxcnt == cnt[temp]) {
samemx++;
}
}
int mxpart = mxcnt - 1; // 分成多少块
int parttodo = partlen - samemx; // 每一块剩余位置
int todonum = parttodo * mxpart; // 总剩余位置
int taskleft = tasksSize - mxcnt * samemx; // 总剩余字符
int idles = MAX(0, todonum - taskleft);
printf("mxcnt=%d,samemx=%d,mxpart=%d,parttodo=%d,todonum=%d,taskleft=%d,idles=%d\n",mxcnt,samemx,mxpart,parttodo,todonum,taskleft,idles);
ret = tasksSize + idles;
return ret;
}