|
| 1 | +/** |
| 2 | + * @param {string[]} taks List of tasks A-Z. |
| 3 | + * @param {number} n Cooling time between running same task. |
| 4 | + * @return {number} Time CPU will take to finish all tasks. |
| 5 | + * @summary Task Scheduler {@link https://leetcode.com/problems/task-scheduler/submissions/} |
| 6 | + * @description Given array of CPU taks and minimum cooling period between same task, return the minimum units of time CPU will take to finish all tasks. |
| 7 | + * Space O(1) - One hash of frequencies up to 26 keys. |
| 8 | + * Time O(n) - N is number of tasks to execute (<26). |
| 9 | + */ |
| 10 | +const leastInterval = (tasks, n) => { |
| 11 | + let maxCount = 0; |
| 12 | + |
| 13 | + const freq = tasks.reduce((acc, val) => { |
| 14 | + acc[val] ? acc[val]++ : (acc[val] = 1); |
| 15 | + if (acc[val] > maxCount) maxCount = acc[val]; |
| 16 | + return acc; |
| 17 | + }, {}); |
| 18 | + |
| 19 | + const maxTasks = Object.keys(freq).reduce((acc, val) => (freq[val] === maxCount ? acc + 1 : acc), 0); |
| 20 | + |
| 21 | + return Math.max(tasks.length, (maxCount - 1) * (n + 1) + maxTasks); |
| 22 | +}; |
0 commit comments