- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 48 lines of Java from the credited upstream file 2247.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 maximumCost(int n, int[][] highways, int k) {3 if (k + 1 > n)4 return -1;5 6 int ans = -1;7 Integer[][] mem = new Integer[n][1 << n];8 List<Pair<Integer, Integer>>[] graph = new List[n];9 Arrays.setAll(graph, i -> new ArrayList<>());10 11 for (int[] h : highways) {12 final int u = h[0];13 final int v = h[1];14 final int w = h[2];15 graph[u].add(new Pair<>(v, w));16 graph[v].add(new Pair<>(u, w));17 }18 19 for (int i = 0; i < n; ++i)20 ans = Math.max(ans, maximumCost(graph, i, 1 << i, k, mem));21 22 return ans;23 }24 25 26 27 private int maximumCost(List<Pair<Integer, Integer>>[] graph, int u, int mask, int k,28 Integer[][] mem) {29 if (Integer.bitCount(mask) == k + 1)30 return 0;31 if (mem[u][mask] != null)32 return mem[u][mask];33 34 int res = -1;35 for (Pair<Integer, Integer> pair : graph[u]) {36 final int v = pair.getKey();37 final int w = pair.getValue();38 if ((mask >> v & 1) == 1)39 continue;40 final int nextCost = maximumCost(graph, v, mask | 1 << v, k, mem);41 if (nextCost != -1)42 res = Math.max(res, w + nextCost);43 }44 45 return mem[u][mask] = res;46 }47}48