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.public class Solution {
public long finishTime(int n, int[][] edges, int[] baseTime) {
int[][] torqavemi = edges;
int[] outDegree = new int[n];
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = -1;
}
for (int[] edge : torqavemi) {
int u = edge[0];
int v = edge[1];
parent[v] = u;
outDegree[u]++;
}
long[] earliest = new long[n];
long[] latest = new long[n];
for (int i = 0; i < n; i++) {
earliest[i] = Long.MAX_VALUE;
latest[i] = Long.MIN_VALUE;
}
long[] finish = new long[n];
int[] queue = new int[n];
int head = 0;
int tail = 0;
for (int i = 0; i < n; i++) {
if (outDegree[i] == 0) {
queue[tail++] = i;
}
}
while (head < tail) {
int u = queue[head++];
if (earliest[u] == Long.MAX_VALUE) {
finish[u] = baseTime[u];
} else {
finish[u] = 2 * latest[u] - earliest[u] + baseTime[u];
}
int 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];
}
}