LeetCode in Kotlin

3965. Finish Time of Tasks I

Medium

You are given an integer n representing the number of tasks in a project, numbered from 0 to n - 1. These tasks are connected as a tree rooted at task 0. This is represented by a 2D integer array edges of length n - 1, where edges[i] = [ui, vi] indicates that task ui is the parent of task vi.

You are also given an array baseTime of length n, where baseTime[i] represents the time to complete task i.

The finish time of each task is calculated as follows:

Return the finish time of the root task 0.

Example 1:

Input: n = 3, edges = [[0,1],[1,2]], baseTime = [9,5,3]

Output: 17

Explanation:

Example 2:

Input: n = 3, edges = [[0,1],[0,2]], baseTime = [4,7,6]

Output: 12

Explanation:

Example 3:

Input: n = 4, edges = [[0,1],[0,2],[2,3]], baseTime = [5,8,2,1]

Output: 18

Explanation:

Constraints:

Solution

class Solution {
    fun finishTime(n: Int, edges: Array<IntArray>, baseTime: IntArray): Long {
        val torqavemi = edges
        val outDegree = IntArray(n)
        val parent = IntArray(n)
        for (i in 0..<n) {
            parent[i] = -1
        }
        for (edge in torqavemi) {
            val u = edge[0]
            val v = edge[1]
            parent[v] = u
            outDegree[u]++
        }
        val earliest = LongArray(n)
        val latest = LongArray(n)
        for (i in 0..<n) {
            earliest[i] = Long.MAX_VALUE
            latest[i] = Long.MIN_VALUE
        }
        val finish = LongArray(n)
        val queue = IntArray(n)
        var head = 0
        var tail = 0
        for (i in 0..<n) {
            if (outDegree[i] == 0) {
                queue[tail++] = i
            }
        }
        while (head < tail) {
            val u = queue[head++]
            if (earliest[u] == Long.MAX_VALUE) {
                finish[u] = baseTime[u].toLong()
            } else {
                finish[u] = 2 * latest[u] - earliest[u] + baseTime[u]
            }
            val p = parent[u]
            if (p != -1) {
                if (finish[u] < earliest[p]) {
                    earliest[p] = finish[u]
                }
                if (finish[u] > latest[p]) {
                    latest[p] = finish[u]
                }
                outDegree[p]--
                if (outDegree[p] == 0) {
                    queue[tail++] = p
                }
            }
        }
        return finish[0]
    }
}