- 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
- 34 lines of Java from the credited upstream file 1473.java.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 minCost(int[] houses, int[][] cost, int m, int n, int target) {3 int[][][] mem = new int[target + 1][m][n + 1];4 5 final int c = minCost(houses, cost, m, n, target, 0, 0, mem);6 return c == MAX ? -1 : c;7 }8 9 private static final int MAX = 1_000_001;10 11 12 13 public int minCost(int[] houses, int[][] cost, int m, int n, int k, int i, int prevColor,14 int[][][] mem) {15 if (i == m || k < 0)16 return k == 0 ? 0 : MAX;17 if (mem[k][i][prevColor] > 0)18 return mem[k][i][prevColor];19 if (houses[i] > 0) 20 return minCost(houses, cost, m, n, k - (prevColor == houses[i] ? 0 : 1), i + 1, houses[i],21 mem);22 23 int ans = MAX;24 25 26 for (int color = 1; color <= n; ++color)27 ans = Math.min(ans, cost[i][color - 1] + minCost(houses, cost, m, n,28 k - (prevColor == color ? 0 : 1), i + 1,29 color, mem));30 31 return mem[k][i][prevColor] = ans;32 }33}34