- 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
- 81 lines of C++ from the credited upstream file 3441.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 6 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 string minCostGoodCaption(string caption) {4 const int n = caption.length();5 if (n < 3)6 return "";7 8 constexpr int kMaxCost = 1'000'000'000;9 10 11 vector<vector<vector<int>>> dp(12 n, vector<vector<int>>(26, vector<int>(3, kMaxCost)));13 14 for (char c = 'a'; c <= 'z'; ++c)15 dp[n - 1][c - 'a'][0] = abs(caption[n - 1] - c);16 17 int minCost = kMaxCost;18 for (int i = n - 2; i >= 0; --i) {19 int newMinCost = kMaxCost;20 for (char c = 'a'; c <= 'z'; ++c) {21 const int j = c - 'a';22 const int changeCost = abs(caption[i] - c);23 dp[i][j][0] = changeCost + minCost;24 dp[i][j][1] = changeCost + dp[i + 1][j][0];25 dp[i][j][2] = changeCost + min(dp[i + 1][j][1], dp[i + 1][j][2]);26 newMinCost = min(newMinCost, dp[i][j][2]);27 }28 minCost = newMinCost;29 }30 31 32 string ans;33 int cost = kMaxCost;34 int letter = -1;35 36 37 for (int c = 25; c >= 0; --c)38 if (dp[0][c][2] <= cost) {39 letter = c;40 cost = dp[0][c][2];41 }42 43 44 cost -= appendLetter(caption, 0, 'a' + letter, ans);45 cost -= appendLetter(caption, 1, 'a' + letter, ans);46 cost -= appendLetter(caption, 2, 'a' + letter, ans);47 48 49 for (int i = 3; i < n;) {50 51 const int nextLetter = getNextLetter(dp, i, cost);52 if (nextLetter < letter || ranges::min(dp[i][letter]) > cost) {53 letter = nextLetter;54 cost -= appendLetter(caption, i, 'a' + letter, ans);55 cost -= appendLetter(caption, i + 1, 'a' + letter, ans);56 cost -= appendLetter(caption, i + 2, 'a' + letter, ans);57 i += 3;58 } else {59 cost -= appendLetter(caption, i, 'a' + letter, ans);60 i += 1;61 }62 }63 64 return ans;65 }66 67 private:68 int getNextLetter(const vector<vector<vector<int>>>& dp, int i, int cost) {69 int nextLetter = 26; 70 for (int c = 25; c >= 0; --c)71 if (cost == dp[i][c][2])72 nextLetter = c;73 return nextLetter;74 }75 76 int appendLetter(const string& caption, int i, char letter, string& ans) {77 ans += letter;78 return abs(caption[i] - letter);79 }80};81