Skip to content

Commit 37b622f

Browse files
authored
Create 1882-process-tasks-using-servers.js
1 parent db64a15 commit 37b622f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* MinPriorityQueue | Simulation
3+
* Time O(n*log(n)) | Space O(n)
4+
* https://leetcode.com/problems/process-tasks-using-servers/
5+
* @param {number[]} servers
6+
* @param {number[]} tasks
7+
* @return {number[]}
8+
*/
9+
var assignTasks = function(servers, tasks) {
10+
11+
const toBeCompleted = new MinPriorityQueue({
12+
compare: (a,b) => {
13+
if(a[0] === b[0]) return a[1] - b[1];
14+
return a[0] - b[0];
15+
}
16+
});
17+
18+
const freeServers = new MinPriorityQueue({
19+
compare: (a,b) => {
20+
if(a[0] === b[0]) return a[1] - b[1];
21+
return a[0] - b[0];
22+
}
23+
});
24+
25+
for(let i = 0; i < servers.length; i++) {
26+
const weight = servers[i];
27+
const idx = i;
28+
freeServers.enqueue([weight, idx]);
29+
}
30+
31+
let sec = 0;
32+
const result = [];
33+
34+
for(let i = 0; i < tasks.length; i++) {
35+
sec = Math.max(i, sec);
36+
37+
// if the we don't have server available then jump to the next imidiate
38+
// time when the server will be available.
39+
if(freeServers.isEmpty()) {
40+
sec = toBeCompleted.front()[0];
41+
}
42+
while(!toBeCompleted.isEmpty() &&
43+
toBeCompleted.front()[0] <= sec
44+
) {
45+
const [endTime, serverIdx] = toBeCompleted.dequeue();
46+
const weight = servers[serverIdx];
47+
freeServers.enqueue([weight, serverIdx]);
48+
}
49+
50+
const [weight, serverIdx] = freeServers.dequeue();
51+
const timeToBeTaken = tasks[i];
52+
result.push(serverIdx);
53+
toBeCompleted.enqueue([sec+timeToBeTaken, serverIdx]);
54+
}
55+
56+
return result;
57+
};

0 commit comments

Comments
 (0)