forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0621-task-scheduler.cs
89 lines (76 loc) · 2.23 KB
/
0621-task-scheduler.cs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
public class Solution
{
private PriorityQueue<FreqClass, int> pq;
private Dictionary<char, int> dictionary;
public int LeastInterval(char[] tasks, int n)
{
// Count tasks in the array
if (n == 0)
return tasks.Length;
dictionary = new Dictionary<char, int>();
foreach (var task in tasks)
{
if (dictionary.ContainsKey(task))
{
dictionary[task]++;
}
else
dictionary.Add(task, 1);
}
pq = new PriorityQueue<FreqClass, int>(new MaxHeap());
var time = 0;
AddItemsToPQ();
while (pq.Count > 0)
{
var list = new List<FreqClass>();
var cnt = 0;
for (var i = 0; i < n + 1; i++)
{
if (pq.Count > 0)
{
var item = pq.Dequeue();
cnt++;
//Console.WriteLine($"Dequeued {item.Task} with frequency : {item.Frequency}");
item.Frequency--;
if (item.Frequency > 0)
list.Add(item);
}
}
for (var i = 0; i < list.Count; i++)
{
var item = list[i];
//Console.WriteLine($"Enqueued {item.Task} with frequency : {item.Frequency}");
pq.Enqueue(item, item.Frequency);
}
time += pq.Count == 0 ? cnt : n + 1;
//Console.WriteLine($"Done with iteration, current time: {time}");
}
return time;
}
private void AddItemsToPQ()
{
foreach (var keyValuePair in dictionary)
{
pq.Enqueue(new FreqClass(keyValuePair.Value, 0, keyValuePair.Key), keyValuePair.Value);
}
}
public class MaxHeap : IComparer<int>
{
public int Compare(int x, int y)
{
return y - x;
}
}
public class FreqClass
{
public int Frequency;
public int IdleTime;
public char Task;
public FreqClass(int frequency, int idleTime, char task)
{
Frequency = frequency;
IdleTime = idleTime;
Task = task;
}
}
}