- 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
- 35 lines of Java from the credited upstream file 2976.java.
- The implementation visibly relies on sequence storage.
- 5 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 minimumCost(String source, String target, char[] original, char[] changed,3 int[] cost) {4 long ans = 0;5 6 long[][] dist = new long[26][26];7 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE));8 9 for (int i = 0; i < cost.length; ++i) {10 final int u = original[i] - 'a';11 final int v = changed[i] - 'a';12 dist[u][v] = Math.min(dist[u][v], cost[i]);13 }14 15 for (int k = 0; k < 26; ++k)16 for (int i = 0; i < 26; ++i)17 if (dist[i][k] < Long.MAX_VALUE)18 for (int j = 0; j < 26; ++j)19 if (dist[k][j] < Long.MAX_VALUE)20 dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);21 22 for (int i = 0; i < source.length(); ++i) {23 if (source.charAt(i) == target.charAt(i))24 continue;25 final int u = source.charAt(i) - 'a';26 final int v = target.charAt(i) - 'a';27 if (dist[u][v] == Long.MAX_VALUE)28 return -1;29 ans += dist[u][v];30 }31 32 return ans;33 }34}35