621. Task Scheduler
Input:
tasks = ["A","A","A","B","B","B"], n = 2
Output:
8
Explanation:
A ->B -> idle -> A -> B ->idle -> A ->B.Last updated
Was this helpful?
Input:
tasks = ["A","A","A","B","B","B"], n = 2
Output:
8
Explanation:
A ->B -> idle -> A -> B ->idle -> A ->B.Last updated
Was this helpful?
Was this helpful?
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int count [26]; fill_n(count, 26, 0); // need to fill each time since OJ seems to re-use the same
// allocated space for running multiple tests
for(char task : tasks){
count[task - 'A']++;
}
sort(begin(count),end(count));
// count how many most frequent chars
int i = 25;
while(i >= 0 && count[i] == count[25])
i--;
int tasks_len = tasks.size();
return max(tasks_len, (count[25] - 1)*(n + 1) + 25 - i);
}
};class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> counter (26);
int max_val = 0;
int maxCount = 0;
for (auto c : tasks){
counter[c - 'A']++;
if(max_val == counter[c - 'A']) maxCount ++;
else if(max_val < counter[c - 'A']){
max_val = counter[c- 'A'];
maxCount = 1;
}
}
int partCount = max_val - 1;
int partLen = n - (maxCount - 1); // could be negative
int emptySlots = partCount * partLen;
int residualTasks = tasks.size() - max_val * maxCount;
int idles = max(0, emptySlots - residualTasks);
return tasks.size() + idles;
}
};