Skip to content

Commit

Permalink
Create 621-Task-Scheduler.js
Browse files Browse the repository at this point in the history
  • Loading branch information
kciccolella committed Jul 22, 2022
1 parent a6650f1 commit d234eba
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions javascript/621-Task-Scheduler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @param {character[]} tasks
* @param {number} n
* @return {number}
*/
var leastInterval = function(tasks, n) {

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;
};

0 comments on commit d234eba

Please sign in to comment.