- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 48 lines of Java from the credited upstream file 3543.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 9 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 maxWeight(int n, int[][] edges, int k, int t) {3 List<Pair<Integer, Integer>>[] graph = new List[n];4 5 Map<Integer, Set<Integer>>[] dp = new Map[n];6 7 for (int u = 0; u < n; ++u) {8 graph[u] = new ArrayList<>();9 dp[u] = new HashMap<>();10 }11 12 for (int[] edge : edges) {13 final int u = edge[0];14 final int v = edge[1];15 final int w = edge[2];16 graph[u].add(new Pair<>(v, w));17 }18 19 for (int u = 0; u < n; ++u) {20 dp[u].putIfAbsent(0, new HashSet<>());21 dp[u].get(0).add(0); 22 }23 24 for (int i = 0; i < k; ++i)25 for (int u = 0; u < n; ++u)26 if (dp[u].containsKey(i))27 for (final int currSum : dp[u].get(i))28 for (Pair<Integer, Integer> pair : graph[u]) {29 final int v = pair.getKey();30 final int w = pair.getValue();31 final int newSum = currSum + w;32 if (newSum < t) {33 dp[v].putIfAbsent(i + 1, new HashSet<>());34 dp[v].get(i + 1).add(newSum);35 }36 }37 38 int ans = -1;39 40 for (int u = 0; u < n; ++u)41 if (dp[u].containsKey(k))42 for (final int sum : dp[u].get(k))43 ans = Math.max(ans, sum);44 45 return ans;46 }47}48