- 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
- 61 lines of Java from the credited upstream file 2911.java.
- The implementation visibly relies on sequence storage, cached states.
- 11 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 int minimumChanges(String s, int k) {3 final int n = s.length();4 5 List<Integer>[] factors = getFactors(n);6 7 int[][] cost = getCost(s, n, factors);8 9 int[][] dp = new int[n + 1][k + 1];10 11 Arrays.stream(dp).forEach(A -> Arrays.fill(A, n));12 dp[n][0] = 0;13 14 for (int i = n - 1; i >= 0; --i)15 for (int j = 1; j <= k; ++j)16 for (int l = i + 1; l < n; ++l)17 dp[i][j] = Math.min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]);18 19 return dp[0][k];20 }21 22 private List<Integer>[] getFactors(int n) {23 List<Integer>[] factors = new List[n + 1];24 for (int i = 1; i <= n; ++i)25 factors[i] = new ArrayList<>(List.of(1));26 for (int d = 2; d < n; ++d)27 for (int i = d * 2; i <= n; i += d)28 factors[i].add(d);29 return factors;30 }31 32 private int[][] getCost(final String s, int n, List<Integer>[] factors) {33 int[][] cost = new int[n][n];34 for (int i = 0; i < n; ++i)35 for (int j = i + 1; j < n; ++j) {36 final int length = j - i + 1;37 int minCost = length;38 for (final int d : factors[length])39 minCost = Math.min(minCost, getCost(s, i, j, d));40 cost[i][j] = minCost;41 }42 return cost;43 }44 45 46 private int getCost(final String s, int i, int j, int d) {47 int cost = 0;48 for (int offset = 0; offset < d; ++offset) {49 int l = i + offset;50 int r = j - d + 1 + offset;51 while (l < r) {52 if (s.charAt(l) != s.charAt(r))53 ++cost;54 l += d;55 r -= d;56 }57 }58 return cost;59 }60}61