- 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
- 78 lines of Java from the credited upstream file 3441.java.
- The implementation visibly relies on sequence storage, cached states.
- 6 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 String minCostGoodCaption(String caption) {3 final int n = caption.length();4 if (n < 3)5 return "";6 7 final int MAX_COST = 1_000_000_000;8 int[][][] dp = new int[n][26][3];9 Arrays.stream(dp).forEach(A -> Arrays.stream(A).forEach(B -> Arrays.fill(B, MAX_COST)));10 11 12 for (char c = 'a'; c <= 'z'; ++c)13 dp[n - 1][c - 'a'][0] = Math.abs(caption.charAt(n - 1) - c);14 15 int minCost = MAX_COST;16 for (int i = n - 2; i >= 0; --i) {17 int newMinCost = MAX_COST;18 for (char c = 'a'; c <= 'z'; ++c) {19 final int j = c - 'a';20 final int changeCost = Math.abs(caption.charAt(i) - c);21 dp[i][j][0] = changeCost + minCost;22 dp[i][j][1] = changeCost + dp[i + 1][j][0];23 dp[i][j][2] = changeCost + Math.min(dp[i + 1][j][1], dp[i + 1][j][2]);24 newMinCost = Math.min(newMinCost, dp[i][j][2]);25 }26 minCost = newMinCost;27 }28 29 30 StringBuilder sb = new StringBuilder();31 int cost = MAX_COST;32 int letter = -1;33 34 35 for (int c = 25; c >= 0; --c)36 if (dp[0][c][2] <= cost) {37 letter = c;38 cost = dp[0][c][2];39 }40 41 42 cost -= appendLetter(caption, 0, (char) ('a' + letter), sb);43 cost -= appendLetter(caption, 1, (char) ('a' + letter), sb);44 cost -= appendLetter(caption, 2, (char) ('a' + letter), sb);45 46 47 for (int i = 3; i < n;) {48 49 final int nextLetter = getNextLetter(dp, i, cost);50 if (nextLetter < letter || Arrays.stream(dp[i][letter]).min().getAsInt() > cost) {51 letter = nextLetter;52 cost -= appendLetter(caption, i, (char) ('a' + letter), sb);53 cost -= appendLetter(caption, i + 1, (char) ('a' + letter), sb);54 cost -= appendLetter(caption, i + 2, (char) ('a' + letter), sb);55 i += 3;56 } else {57 cost -= appendLetter(caption, i, (char) ('a' + letter), sb);58 i += 1;59 }60 }61 62 return sb.toString();63 }64 65 private int getNextLetter(int[][][] dp, int i, int cost) {66 int nextLetter = 26;67 for (int c = 25; c >= 0; --c)68 if (cost == dp[i][c][2])69 nextLetter = c;70 return nextLetter;71 }72 73 private int appendLetter(String caption, int i, char letter, StringBuilder sb) {74 sb.append(letter);75 return Math.abs(caption.charAt(i) - letter);76 }77}78