Java easy DFS solution with comments (construct tree using hashmap)
	public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
		int[] max = new int[]{Integer.MIN_VALUE}; // int array with 1 num only, dynamically storing global max spreading time
		Map<Integer, Set<Integer>> map = new HashMap<>();
		//map to store employee:subordinate relation
		//construct the map - 
		for (int i = 0; i < n; i++) {
			map.put(i, new HashSet<Integer>());
		}
		for (int i = 0; i < n; i++) {
			if (manager[i] == -1) {
				continue;
			}
			map.get(manager[i]).add(i);    
		}
		//call dfs function on company head (tree root)
		dfs(map, headID, informTime, 0, max);
		return max[0]; // return the global max spreading time

	}
	public void dfs(Map<Integer, Set<Integer>> map, int id, int[] informTime, int accuTime, int[] max) {
		//base case/exit condition: id has no subordinate - it's a leaf node
		//update max spreading time if it's larger than current max.
		if (map.get(id).size() == 0) {
			max[0] = Math.max(accuTime, max[0]);
			return;
		}
		// dfs: expand to id's next direct subordinates, add accumulated spreading time accordingly.
		for (int i : map.get(id)) {
			dfs(map, i, informTime, accuTime + informTime[id], max);
		}
		return;
	}
Comments (0)