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:
baseTime[i].earliest be the minimum finish time among its children, and latest be the maximum finish time among its children.ownDuration be (latest - earliest) + baseTime[i].i is latest + ownDuration.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:

baseTime[2] = 3.earliest = latest = 3ownDuration = (latest - earliest) + baseTime[1] = 53 + 5 = 8earliest = latest = 8ownDuration = (latest - earliest) + baseTime[0] = 98 + 9 = 17Example 2:
Input: n = 3, edges = [[0,1],[0,2]], baseTime = [4,7,6]
Output: 12
Explanation:

baseTime[1] = 7.baseTime[2] = 6.earliest = 6, latest = 7ownDuration = (latest - earliest) + baseTime[0] = (7 - 6) + 4 = 5latest + ownDuration = 7 + 5 = 12Example 3:
Input: n = 4, edges = [[0,1],[0,2],[2,3]], baseTime = [5,8,2,1]
Output: 18
Explanation:
baseTime[1] = 8.baseTime[3] = 1.earliest = latest = 1ownDuration = (latest - earliest) + baseTime[2] = 0 + 2 = 2latest + ownDuration = 1 + 2 = 3earliest = 3, latest = 8ownDuration = (latest - earliest) + baseTime[0] = (8 - 3) + 5 = 10latest + ownDuration = 8 + 10 = 18Constraints:
1 <= n <= 105edges.length = n - 1edges[i] == [ui, vi]0 <= ui, vi <= n - 1ui != viedges represents a valid tree.baseTime.length == n1 <= baseTime[i] <= 105253.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]
}
}