- 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
- 76 lines of Python from the credited upstream file 3441.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit 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 3 def minCostGoodCaption(self, caption: str) -> str:4 n = len(caption)5 if n < 3:6 return ''7 8 MAX_COST = 1_000_000_0009 10 11 dp = [[[MAX_COST] * 3 for _ in range(26)] for _ in range(n)]12 13 for c in range(26):14 dp[-1][c][0] = abs(string.ascii_lowercase.index(caption[-1]) - c)15 16 minCost = MAX_COST17 18 for i in range(n - 2, -1, -1):19 newMinCost = MAX_COST20 for c in range(26):21 changeCost = abs(string.ascii_lowercase.index(caption[i]) - c)22 dp[i][c][0] = changeCost + minCost23 dp[i][c][1] = changeCost + dp[i + 1][c][0]24 dp[i][c][2] = changeCost + min(dp[i + 1][c][1], dp[i + 1][c][2])25 newMinCost = min(newMinCost, dp[i][c][2])26 minCost = newMinCost27 28 29 ans = []30 cost = MAX_COST31 letter = -132 33 34 for c in range(25, -1, -1):35 if dp[0][c][2] <= cost:36 letter = c37 cost = dp[0][c][2]38 39 40 cost -= self._appendLetter(caption, 0, chr(ord('a') + letter), ans)41 cost -= self._appendLetter(caption, 1, chr(ord('a') + letter), ans)42 cost -= self._appendLetter(caption, 2, chr(ord('a') + letter), ans)43 44 45 i = 346 while i < n:47 nextLetter = self._getNextLetter(dp, i, cost)48 if nextLetter < letter or min(dp[i][letter]) > cost:49 letter = nextLetter50 cost -= self._appendLetter(caption, i, chr(ord('a') + letter), ans)51 cost -= self._appendLetter(caption, i + 1, chr(ord('a') + letter), ans)52 cost -= self._appendLetter(caption, i + 2, chr(ord('a') + letter), ans)53 i += 354 else:55 cost -= self._appendLetter(caption, i, chr(ord('a') + letter), ans)56 i += 157 58 return ''.join(ans)59 60 def _getNextLetter(self, dp: list[list[list[int]]], i: int, cost: int) -> int:61 nextLetter = 2662 for c in range(25, -1, -1):63 if cost == dp[i][c][2]:64 nextLetter = c65 return nextLetter66 67 def _appendLetter(68 self,69 caption: str,70 i: int,71 letter: str,72 ans: list[str]73 ) -> int:74 ans.append(letter)75 return abs(ord(caption[i]) - ord(letter))76