- 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
- 38 lines of Java from the credited upstream file 3429.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 long minCost(int n, int[][] costs) {3 final int INVALID_COLOR = 3;4 Long[][][] mem = new Long[n / 2][4][4];5 return minCost(costs, 0, INVALID_COLOR, INVALID_COLOR, mem);6 }7 8 private long minCost(int[][] costs, int i, int prevLeftColor, int prevRightColor,9 Long[][][] mem) {10 if (i == costs.length / 2)11 return 0;12 if (mem[i][prevLeftColor][prevRightColor] != null)13 return mem[i][prevLeftColor][prevRightColor];14 15 long res = Long.MAX_VALUE;16 17 for (final int leftColor : getValidColors(prevLeftColor))18 for (final int rightColor : getValidColors(prevRightColor)) {19 if (leftColor == rightColor)20 continue;21 final long leftCost = costs[i][leftColor];22 final long rightCost = costs[costs.length - 1 - i][rightColor];23 res =24 Math.min(res, leftCost + rightCost + minCost(costs, i + 1, leftColor, rightColor, mem));25 }26 27 return mem[i][prevLeftColor][prevRightColor] = res;28 }29 30 private List<Integer> getValidColors(int prevColor) {31 List<Integer> validColors = new ArrayList<>();32 for (int color = 0; color < 3; ++color)33 if (color != prevColor)34 validColors.add(color);35 return validColors;36 }37}38