LeetCode in Kotlin

1882. Process Tasks Using Servers

Medium

You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the jth task in seconds.

Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.

At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.

If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.

A server that is assigned task j at second t will be free again at second t + tasks[j].

Build an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to.

Return the array ans.

Example 1:

Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]

Output: [2,2,0,2,1,2]

Explanation: Events in chronological order go as follows:

Example 2:

Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]

Output: [1,4,1,4,1,3,2]

Explanation: Events in chronological order go as follows:

Constraints:

Solution

import java.util.PriorityQueue

class Solution {
    fun assignTasks(servers: IntArray, tasks: IntArray): IntArray {
        val serverq =
            PriorityQueue { i1: Int, i2: Int -> if (servers[i1] != servers[i2]) servers[i1] - servers[i2] else i1 - i2 }
        for (i in servers.indices) {
            serverq.offer(i)
        }
        val activetaskq = PriorityQueue { i1: IntArray, i2: IntArray -> i1[1] - i2[1] }
        var time = 0
        val res = IntArray(tasks.size)
        for (i in tasks.indices) {
            time = Math.max(time, i)
            while (activetaskq.isNotEmpty() && activetaskq.peek()[1] <= i) {
                val task = activetaskq.poll()
                serverq.offer(task[0])
            }
            if (serverq.isEmpty()) {
                val toptask = activetaskq.peek()
                while (activetaskq.isNotEmpty() && activetaskq.peek()[1] == toptask[1]) {
                    val task = activetaskq.poll()
                    serverq.offer(task[0])
                }
                time = toptask[1]
            }
            val server = serverq.poll()
            res[i] = server
            activetaskq.offer(intArrayOf(server, time + tasks[i]))
        }
        return res
    }
}