- 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
- 30 lines of Java from the credited upstream file 2746.java.
- The implementation visibly relies on sequence storage.
- No explicit 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 minimizeConcatenatedLength(String[] words) {3 int[][][] mem = new int[words.length][26][26];4 return words[0].length() + minimizeConcatenatedLength(words, 1, words[0].charAt(0),5 words[0].charAt(words[0].length() - 1),6 mem);7 }8 9 private int minimizeConcatenatedLength(String[] words, int i, char first, char last,10 int[][][] mem) {11 if (i == words.length)12 return 0;13 final int j = first - 'a';14 final int k = last - 'a';15 if (mem[i][j][k] > 0)16 return mem[i][j][k];17 final char nextFirst = words[i].charAt(0);18 final char nextLast = words[i].charAt(words[i].length() - 1);19 return mem[i][j][k] = 20 words[i].length() + 21 Math.min(22 23 minimizeConcatenatedLength(words, i + 1, first, nextLast, mem) -24 (last == nextFirst ? 1 : 0),25 26 minimizeConcatenatedLength(words, i + 1, nextFirst, last, mem) -27 (first == nextLast ? 1 : 0));28 }29}30