Skip to content

Commit 981adc7

Browse files
authored
Merge pull request neetcode-gh#585 from kciccolella/leetcode621
Create 621-Task-Scheduler.js
2 parents a6650f1 + d234eba commit 981adc7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

javascript/621-Task-Scheduler.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {character[]} tasks
3+
* @param {number} n
4+
* @return {number}
5+
*/
6+
var leastInterval = function(tasks, n) {
7+
8+
const charMap = new Map();
9+
let maxCharCount = 0;
10+
let maxChar = tasks[0];
11+
12+
for (let char of tasks) {
13+
charMap.set(char, (charMap.get(char) || 0) + 1);
14+
if (charMap.get(char) > maxCharCount) {
15+
maxCharCount = charMap.get(char);
16+
maxChar = char;
17+
}
18+
}
19+
20+
let idleCount = (maxCharCount - 1) * n;
21+
22+
charMap.forEach((count, char) => {
23+
// 'return' inside forEach() serve as 'continue'
24+
if (char === maxChar) return;
25+
if (count === maxCharCount) idleCount -= (count - 1);
26+
else idleCount -= count;
27+
});
28+
29+
if (idleCount <= 0) return tasks.length;
30+
return tasks.length + idleCount;
31+
};

0 commit comments

Comments
 (0)