- 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
- 49 lines of C++ from the credited upstream file 3389.cpp.
- 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:3 int makeStringGood(string s) {4 int ans = s.length();5 vector<int> count(26);6 7 for (const char c : s)8 ++count[c - 'a'];9 10 const int mx = ranges::max(count);11 for (int target = 1; target <= mx; ++target)12 ans = min(ans, getMinOperations(count, target));13 14 return ans;15 }16 17 private:18 int getMinOperations(const vector<int>& count, int target) {19 20 21 vector<int> dp(27);22 23 for (int i = 25; i >= 0; --i) {24 25 const int deleteAllToZero = count[i];26 27 const int deleteOrInsertToTarget = abs(target - count[i]);28 dp[i] = min(deleteAllToZero, deleteOrInsertToTarget) + dp[i + 1];29 if (i + 1 < 26 && count[i + 1] < target) {30 const int nextDeficit = target - count[i + 1];31 32 const int needToChange =33 count[i] > target ? count[i] - target : count[i];34 const int changeToTarget =35 nextDeficit > needToChange36 37 38 ? needToChange + (nextDeficit - needToChange)39 40 41 : nextDeficit + (needToChange - nextDeficit);42 dp[i] = min(dp[i], changeToTarget + dp[i + 2]);43 }44 }45 46 return dp[0];47 }48};49