Approach
Depth-first search
For Maximum Path Quality of a Graph, 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
- 39 lines of Java from the credited upstream file 2065.java.
- The implementation visibly relies on sequence storage.
- 2 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 maximalPathQuality(int[] values, int[][] edges, int maxTime) {3 final int n = values.length;4 List<Pair<Integer, Integer>>[] graph = new List[n];5 int[] seen = new int[n];6 seen[0] = 1;7 Arrays.setAll(graph, i -> new ArrayList<>());8 9 for (int[] edge : edges) {10 final int u = edge[0];11 final int v = edge[1];12 final int time = edge[2];13 graph[u].add(new Pair<>(v, time));14 graph[v].add(new Pair<>(u, time));15 }16 17 dfs(graph, values, 0, values[0], maxTime, seen);18 return ans;19 }20 21 private int ans = 0;22 23 private void dfs(List<Pair<Integer, Integer>>[] graph, int[] values, int u, int quality,24 int remainingTime, int[] seen) {25 if (u == 0)26 ans = Math.max(ans, quality);27 for (Pair<Integer, Integer> pair : graph[u]) {28 final int v = pair.getKey();29 final int time = pair.getValue();30 if (time > remainingTime)31 continue;32 final int newQuality = quality + values[v] * (seen[v] == 0 ? 1 : 0);33 ++seen[v];34 dfs(graph, values, v, newQuality, remainingTime - time, seen);35 --seen[v];36 }37 }38}39