Skip to content

Commit be87794

Browse files
committed
Add solution #621
1 parent 420ace8 commit be87794

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@
223223
605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy|
224224
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
225225
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
226+
621|[Task Scheduler](./0621-task-scheduler.js)|Medium|
226227
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|
227228
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|
228229
645|[Set Mismatch](./0645-set-mismatch.js)|Medium|

solutions/0621-task-scheduler.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 621. Task Scheduler
3+
* https://leetcode.com/problems/task-scheduler/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n.
7+
* Each CPU interval can be idle or allow the completion of one task. Tasks can be completed
8+
* in any order, but there's a constraint: there has to be a gap of at least n intervals
9+
* between two tasks with the same label.
10+
*
11+
* Return the minimum number of CPU intervals required to complete all tasks.
12+
*/
13+
14+
/**
15+
* @param {character[]} tasks
16+
* @param {number} n
17+
* @return {number}
18+
*/
19+
var leastInterval = function(tasks, n) {
20+
const map = new Map();
21+
let maxValue = 0;
22+
let maxCount = 0;
23+
24+
tasks.forEach(key => {
25+
const value = map.has(key) ? map.get(key) + 1 : 1;
26+
map.set(key, value);
27+
28+
if (value > maxValue) {
29+
maxValue = value;
30+
maxCount = 1;
31+
} else if (value === maxValue) {
32+
maxCount++;
33+
}
34+
});
35+
36+
return Math.max(tasks.length, (maxValue - 1) * (n + 1) + maxCount);
37+
};

0 commit comments

Comments
 (0)