-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask-assignment.js
More file actions
43 lines (34 loc) · 1.13 KB
/
task-assignment.js
File metadata and controls
43 lines (34 loc) · 1.13 KB
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
// k numOfWorkers
// array of positive integers
// time O(n(log n)) because we need to sort the array
// space O(n) where n is the number of elements in the tasks array
// greedy algorithm
function taskAssignment(k, tasks) {
const taskDurationToIndices = getTaskDurationToIndices(tasks);
const sortedTasks = [...tasks].sort((a, b) => a - b);
const assigments = [];
let right = tasks.length - 1;
let left = 0;
while(left < right) {
const leftValue = taskDurationToIndices[sortedTasks[left]].pop();
const rightValue = taskDurationToIndices[sortedTasks[right]].pop()
assigments.push([leftValue, rightValue])
left++;
right--;
}
return assigments;
}
function getTaskDurationToIndices(tasks) {
const taskDurationToIndices = {};
for(let idx in tasks) {
if(tasks[idx] in taskDurationToIndices) {
taskDurationToIndices[tasks[idx]].unshift(idx);
} else {
taskDurationToIndices[tasks[idx]] = [idx];
}
}
return taskDurationToIndices;
}
const k = 3;
const tasks = [1, 3, 5, 3, 1, 4];
console.log(taskAssignment(k, tasks));