Approach
Depth-first search
For Time Taken to Mark All Nodes, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 83 lines of Java from the credited upstream file 3241.java.
- The implementation visibly relies on sequence storage, cached states.
- 4 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] timeTaken(int[][] edges) {3 final int n = edges.length + 1;4 int[] ans = new int[n];5 List<Integer>[] tree = new List[n];6 7 8 9 Top2[] dp = new Top2[n];10 11 for (int i = 0; i < n; ++i) {12 tree[i] = new ArrayList<>();13 dp[i] = new Top2();14 }15 16 for (int[] edge : edges) {17 final int u = edge[0];18 final int v = edge[1];19 tree[u].add(v);20 tree[v].add(u);21 }22 23 dfs(tree, 0, -1, dp);24 reroot(tree, 0, -1, 0, dp, ans);25 return ans;26 }27 28 private record Node(int node, int time) {29 Node() {30 this(0, 0);31 }32 }33 34 private record Top2(Node max1, Node max2) {35 Top2() {36 this(new Node(), new Node());37 }38 }39 40 41 private int getTime(int u) {42 return u % 2 == 0 ? 2 : 1;43 }44 45 46 47 48 49 50 51 private int dfs(List<Integer>[] tree, int u, int prev, Top2[] dp) {52 Node max1 = new Node();53 Node max2 = new Node();54 for (final int v : tree[u]) {55 if (v == prev)56 continue;57 final int time = dfs(tree, v, u, dp) + getTime(v);58 if (time >= max1.time()) {59 max2 = max1;60 max1 = new Node(v, time);61 } else if (time > max2.time()) {62 max2 = new Node(v, time);63 }64 }65 dp[u] = new Top2(max1, max2);66 return max1.time();67 }68 69 70 71 private void reroot(List<Integer>[] tree, int u, int prev, int maxTime, Top2[] dp, int[] ans) {72 ans[u] = Math.max(maxTime, dp[u].max1().time());73 for (final int v : tree[u]) {74 if (v == prev)75 continue;76 final int newMaxTime =77 getTime(u) +78 Math.max(maxTime, dp[u].max1().node() == v ? dp[u].max2().time() : dp[u].max1().time());79 reroot(tree, v, u, newMaxTime, dp, ans);80 }81 }82}83