forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0621-task-scheduler.cpp
73 lines (63 loc) · 2.05 KB
/
0621-task-scheduler.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Given array of tasks & cooldown b/w same tasks, return least # of units of time
Ex. tasks = ["A","A","A","B","B","B"] n = 2 -> 8 (A->B->idle->A->B->idle->A->B)
Key is to determine # of idles, greedy: always arrange task w/ most freq first
3A, 2B, 1C -> A??A??A -> AB?AB?A -> ABCAB#A, since A most freq, needs most idles
Time: O(n)
Space: O(1)
*/
/*
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> counter(26);
int maxCount = 0;
int maxCountFrequency = 0;
for (int i = 0; i < tasks.size(); i++) {
counter[tasks[i] - 'A']++;
int currCount = counter[tasks[i] - 'A'];
if (maxCount == currCount) {
maxCountFrequency++;
} else if (maxCount < currCount) {
maxCount = currCount;
maxCountFrequency = 1;
}
}
int partCount = maxCount - 1;
int partLength = n - (maxCountFrequency - 1);
int emptySlots = partCount * partLength;
int availableTasks = tasks.size() - maxCount * maxCountFrequency;
int idles = max(0, emptySlots - availableTasks);
return tasks.size() + idles;
}
};
*/
// Time O(n * cooldown)
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
priority_queue<int> pq;
queue<vector<int>> q;
vector<int> counter(26);
for (int i = 0; i < tasks.size(); ++i)
++counter[tasks[i] - 'A'];
for (int i = 0; i < 26; ++i){
if (counter[i])
pq.push(counter[i]);
}
int time = 0;
while (!q.empty() || !pq.empty()){
++time;
if (!pq.empty()){
if (pq.top() - 1)
q.push({pq.top() - 1, time + n});
pq.pop();
}
if (!q.empty() && q.front()[1] == time){
pq.push(q.front()[0]);
q.pop();
}
}
return time;
}
};