Minimum Cost Good Caption Problem
Description
LeetCode Problem 3441.
You are given a string caption of length n. A good caption is a string where every character appears in groups of at least 3 consecutive occurrences.
For example:
"aaabbb"and"aaaaccc"are good captions."aabbb"and"ccccd"are not good captions.
You can perform the following operation any number of times:
Choose an index i (where 0 <= i < n) and change the character at that index to either:
- The character immediately before it in the alphabet (if
caption[i] != 'a'). - The character immediately after it in the alphabet (if
caption[i] != 'z').
Your task is to convert the given caption into a good caption using the minimum number of operations, and return it. If there are multiple possible good captions, return the lexicographically smallest one among them. If it is impossible to create a good caption, return an empty string "".
Example 1:
Input: caption = "cdcd"
Output: "cccc"
Explanation:
It can be shown that the given caption cannot be transformed into a good caption with fewer than 2 operations. The possible good captions that can be created using exactly 2 operations are:
- "dddd": Change caption[0] and caption[2] to their next character 'd'.
- "cccc": Change caption[1] and caption[3] to their previous character 'c'.
Since "cccc" is lexicographically smaller than "dddd", return "cccc".
Example 2:
Input: caption = "aca"
Output: "aaa"
Explanation:
It can be proven that the given caption requires at least 2 operations to be transformed into a good caption. The only good caption that can be obtained with exactly 2 operations is as follows:
- Operation 1: Change caption[1] to 'b'. caption = "aba".
- Operation 2: Change caption[1] to 'a'. caption = "aaa".
Thus, return "aaa".
Example 3:
Input: caption = "bc"
Output: ""
Explanation:
It can be shown that the given caption cannot be converted to a good caption by using any number of operations.
Constraints:
1 <= caption.length <= 5 * 10^4captionconsists only of lowercase English letters.
Solution
Approach: Dynamic Programming from the Right
A good caption is a sequence of runs of equal letters, each of length at least 3. Changing a letter costs its distance in the alphabet.
Define the state by the previous letter c and how long the current run is, capped at 3 (1, 2, or at least 3). Let h[r][i][c] be the minimum cost to finish positions i..n-1 from that state. At position i we either continue the run with c (cost |caption[i] - c|, run length grows) or, if the run already has length 3, start a run with any letter d (cost |caption[i] - d| + h[1][i+1][d]). The best start over all d is computed once per position, so each position costs O(26). The base case is h[3][n] = 0 and h[1][n] = h[2][n] = infinity.
If the total is infinite (for example n < 3) return "". Otherwise rebuild the string from the left: at each position try the letters from a to z and take the first one whose cost plus the cost of the rest equals what is still needed. This gives the lexicographically smallest caption among those with the minimum cost.
Complexity: O(26 * n) time and space.
class Solution:
def minCostGoodCaption(self, caption: str) -> str:
n = len(caption)
if n < 3:
return ""
INF = 10**9
s = [ord(c) - 97 for c in caption]
costs = [[abs(a - c) for c in range(26)] for a in range(26)]
# h1[i][c], h2[i][c], h3[i][c]: min cost of positions i.. when position i-1 has
# letter c and the run ending there has length 1, 2, or at least 3
h1 = [None] * (n + 1)
h2 = [None] * (n + 1)
h3 = [None] * (n + 1)
h1[n] = [INF] * 26
h2[n] = [INF] * 26
h3[n] = [0] * 26
for i in range(n - 1, -1, -1):
cost = costs[s[i]]
n1, n2, n3 = h1[i + 1], h2[i + 1], h3[i + 1]
sw = min([cost[d] + n1[d] for d in range(26)]) # start a new run at i
h1[i] = [cost[c] + n2[c] for c in range(26)]
h2[i] = [cost[c] + n3[c] for c in range(26)]
h3[i] = [min(cost[c] + n3[c], sw) for c in range(26)]
H = [None, h1, h2, h3]
total = min([costs[s[0]][d] + h1[1][d] for d in range(26)])
if total >= INF:
return ""
res = []
c, r, rest = -1, 3, total
for i in range(n):
for d in range(26):
if d == c:
nr = min(r + 1, 3)
elif r == 3:
nr = 1
else:
continue
cost = costs[s[i]][d]
if cost + H[nr][i + 1][d] == rest:
res.append(chr(97 + d))
rest -= cost
c, r = d, nr
break
return "".join(res)