- 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
- 45 lines of Java from the credited upstream file 3389.java.
- The implementation visibly relies on sequence storage, cached states.
- 3 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 makeStringGood(String s) {3 int ans = s.length();4 int[] count = new int[26];5 6 for (final char c : s.toCharArray())7 ++count[c - 'a'];8 9 final int maxCount = Arrays.stream(count).max().getAsInt();10 for (int target = 1; target <= maxCount; ++target)11 ans = Math.min(ans, getMinOperations(count, target));12 13 return ans;14 }15 16 private int getMinOperations(int[] count, int target) {17 18 19 int[] dp = new int[27];20 21 for (int i = 25; i >= 0; --i) {22 23 int deleteAllToZero = count[i];24 25 int deleteOrInsertToTarget = Math.abs(target - count[i]);26 dp[i] = Math.min(deleteAllToZero, deleteOrInsertToTarget) + dp[i + 1];27 if (i + 1 < 26 && count[i + 1] < target) {28 final int nextDeficit = target - count[i + 1];29 30 final int needToChange = count[i] <= target ? count[i] : count[i] - target;31 final int changeToTarget = (nextDeficit > needToChange)32 33 34 ? needToChange + (nextDeficit - needToChange)35 36 37 : nextDeficit + (needToChange - nextDeficit);38 dp[i] = Math.min(dp[i], changeToTarget + dp[i + 2]);39 }40 }41 42 return dp[0];43 }44}45