|
| 1 | +// https://leetcode.com/problems/time-needed-to-inform-all-employees |
| 2 | +// T: O(n) |
| 3 | +// S: O(n) |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +public class TimeNeededToInformAllEmployees { |
| 11 | + private static final class TreeNode { |
| 12 | + int val; |
| 13 | + List<TreeNode> subordinates = new ArrayList<>(); |
| 14 | + |
| 15 | + TreeNode(int val) { |
| 16 | + this.val = val; |
| 17 | + } |
| 18 | + |
| 19 | + private boolean hasSubordinates() { |
| 20 | + return subordinates.size() > 0; |
| 21 | + } |
| 22 | + |
| 23 | + private void addSubordinate(TreeNode subordinate) { |
| 24 | + this.subordinates.add(subordinate); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) { |
| 29 | + TreeNode company = createEmployeeGraph(headID, manager); |
| 30 | + return timeNeededForInformationDispersal(company, informTime); |
| 31 | + } |
| 32 | + |
| 33 | + private int timeNeededForInformationDispersal(TreeNode root, int[] informTime) { |
| 34 | + if (root == null || !root.hasSubordinates()) return 0; |
| 35 | + int timeTaken = 0; |
| 36 | + for (TreeNode subordinate : root.subordinates) { |
| 37 | + timeTaken = Math.max(timeTaken, timeNeededForInformationDispersal(subordinate, informTime)); |
| 38 | + } |
| 39 | + return timeTaken + informTime[root.val]; |
| 40 | + } |
| 41 | + |
| 42 | + private TreeNode createEmployeeGraph(int headIndex, int[] managers) { |
| 43 | + final TreeNode root = new TreeNode(headIndex); |
| 44 | + final Map<Integer, TreeNode> employees = new HashMap<>(); |
| 45 | + employees.put(headIndex, root); |
| 46 | + for (int i = 0 ; i < managers.length ; i++) { |
| 47 | + int managerId = managers[i]; |
| 48 | + if (managerId == -1) continue; |
| 49 | + TreeNode manager = employees.getOrDefault(managerId, new TreeNode(managerId)); |
| 50 | + TreeNode subordinate = employees.getOrDefault(i, new TreeNode(i)); |
| 51 | + manager.addSubordinate(subordinate); |
| 52 | + if (!employees.containsKey(managerId)) employees.put(managerId, manager); |
| 53 | + if (!employees.containsKey(i)) employees.put(i, subordinate); |
| 54 | + } |
| 55 | + return root; |
| 56 | + } |
| 57 | +} |
0 commit comments