Suppose I have a string of A's and B's. I can either remove a character from either end of the string for a cost of 1, or I can remove any character from the middle for a cost of 2. What's the minimum cost to create a string of only A's?
For example, if I have the string "BBABAA", then the minimum cost to remove is 4, since I would remove the B's from the left for a cost of 2, then remove the singular B from the right for a cost of 2, resulting in a combined cost of 4.
I attempted a top-down solution with caching below:
def MRC_helper(s, count, cache):
if count == 0:
cache[s] = 0
cache[s[::-1]] = 0
return 0
if s in cache:
return cache[s]
min_cost = len(s)
for i in range(len(s)):
new_count = count - int(s[i] == 'B')
new_s = s[:i]+s[i+1:]
if i == 0 or i == len(s)-1:
min_cost = min(min_cost, 1 + MRC_helper(new_s, new_count, cache))
elif s[i] == 'B':
min_cost = min(min_cost, 2 + MRC_helper(new_s, new_count, cache))
cache[s] = min_cost
cache[s[::-1]] = min_cost
return min_cost
def minRemovalCost(s):
min_cost = MRC_helper(s, s.count('B'), {})
return min_cost
The idea is pretty simple: for each character that you can remove, try to remove it and calculate the cost to transform the resulting substring. Then calculate the minimum cost move and cache it. I also cache the string forwards and backwards since it's the same thing. My friend said that it could be done greedily, but I disagree. Can anybody shed some light on a better solution than mine?