forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path621-Task-Scheduler.ts
More file actions
32 lines (28 loc) · 818 Bytes
/
621-Task-Scheduler.ts
File metadata and controls
32 lines (28 loc) · 818 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function leastInterval(tasks: string[], n: number): number {
const charMap = new Map();
let maxCharCount = 0;
let maxChar = tasks[0];
for (let char of tasks) {
charMap.set(char, (charMap.get(char) || 0) + 1);
if (charMap.get(char) > maxCharCount) {
maxCharCount = charMap.get(char);
maxChar = char;
}
}
let idleCount = (maxCharCount - 1) * n;
charMap.forEach((count, char) => {
// 'return' inside forEach() serve as 'continue'
if (char === maxChar) {
return;
}
if (count === maxCharCount) {
idleCount -= count - 1;
} else {
idleCount -= count;
}
});
if (idleCount <= 0) {
return tasks.length;
}
return tasks.length + idleCount;
}