LeetCode-in-Java

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

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];
    }
}