- 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
- 69 lines of Java from the credited upstream file 2977.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 9 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 long minimumCost(String source, String target, String[] original, String[] changed,3 int[] cost) {4 Set<Integer> subLengths = getSubLengths(original);5 Map<String, Integer> subToId = getSubToId(original, changed);6 final int subCount = subToId.size();7 8 9 long[][] dist = new long[subCount][subCount];10 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE));11 12 13 long[] dp = new long[source.length() + 1];14 Arrays.fill(dp, Long.MAX_VALUE);15 16 for (int i = 0; i < cost.length; ++i) {17 final int u = subToId.get(original[i]);18 final int v = subToId.get(changed[i]);19 dist[u][v] = Math.min(dist[u][v], (long) cost[i]);20 }21 22 for (int k = 0; k < subCount; ++k)23 for (int i = 0; i < subCount; ++i)24 if (dist[i][k] < Long.MAX_VALUE)25 for (int j = 0; j < subCount; ++j)26 if (dist[k][j] < Long.MAX_VALUE)27 dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);28 29 dp[0] = 0;30 31 for (int i = 0; i < source.length(); ++i) {32 if (dp[i] == Long.MAX_VALUE)33 continue;34 if (target.charAt(i) == source.charAt(i))35 dp[i + 1] = Math.min(dp[i + 1], dp[i]);36 for (int subLength : subLengths) {37 if (i + subLength > source.length())38 continue;39 String subSource = source.substring(i, i + subLength);40 String subTarget = target.substring(i, i + subLength);41 if (!subToId.containsKey(subSource) || !subToId.containsKey(subTarget))42 continue;43 final int u = subToId.get(subSource);44 final int v = subToId.get(subTarget);45 if (dist[u][v] < Long.MAX_VALUE)46 dp[i + subLength] = Math.min(dp[i + subLength], dp[i] + dist[u][v]);47 }48 }49 50 return dp[source.length()] == Long.MAX_VALUE ? -1 : dp[source.length()];51 }52 53 private Map<String, Integer> getSubToId(String[] original, String[] changed) {54 Map<String, Integer> subToId = new HashMap<>();55 for (final String s : original)56 subToId.putIfAbsent(s, subToId.size());57 for (final String s : changed)58 subToId.putIfAbsent(s, subToId.size());59 return subToId;60 }61 62 private Set<Integer> getSubLengths(String[] original) {63 Set<Integer> subLengths = new HashSet<>();64 for (final String s : original)65 subLengths.add(s.length());66 return subLengths;67 }68}69