Skip to content

Create 1882-process-tasks-using-servers.java #2497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions java/1882-process-tasks-using-servers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public int[] assignTasks(int[] servers, int[] tasks) {
int[] res = new int[tasks.length];

// [weight, index]
Queue<int[]> available = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
for (int i = 0; i < servers.length; i++)
available.add(new int[] { servers[i], i });

int time = 0;
int nextTask = 0;
// [weight, index, done time]
Queue<int[]> unavail = new PriorityQueue<>((a, b) -> a[2] - b[2]);
while (nextTask < tasks.length) {
// release available servers
while (!unavail.isEmpty() && unavail.peek()[2] <= time) {
int[] curr = unavail.poll();
available.add(new int[] { curr[0], curr[1] });
}

// assign task(s)
while (!available.isEmpty() && nextTask < time && nextTask != tasks.length) {
int[] curr = available.poll();
unavail.add(new int[] { curr[0], curr[1], time + tasks[nextTask] });
res[nextTask++] = curr[1];
}

// advance time
if (available.isEmpty())
time = unavail.peek()[2];
else
time++;
}
return res;
}
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy