Program to determine the minimum cost to build a given string in python


Suppose, we have to build a string 'str' that is of length n. To build the string, we can perform two operations.

  • A character can be added to the end of str for cost a.
  • A substring sub_str can be added to the end of the str for cost r.

We have to calculate the minimum cost of building the string str.

So, if the input is like a = 5, r = 4, str = 'tpoint', then the output will be 29.

To build the string 'tpoint', the cost is described below −

str = 't'; a new character added, therefore the cost is 5.
str = 'tp'; a new character added, therefore the cost is 5.
str = 'tpo'; a new character added, therefore the cost is 5.
str = 'tpoi'; a new character added, therefore the cost is 5.
str = 'tpoin'; a new character added, therefore the cost is 5.
str = 'tpoint'; substring 't' is added, therefore the cost is 4.

Total cost is 5 + 5 + 5 + 5 + 5 + 4 = 29.

To solve this, we will follow these steps −

  • size := size of str
  • largest := a new list
  • low := 0
  • for upp in range 1 to size+1, do
    • while str[from index low to index upp] is not present in str[from index 0 to index low], do
      • low := low + 1
    • insert (upp - low) at the end of largest
  • c := a new list containing a
  • for i in range 1 to size, do
    • if largest[i] is same as 0, then
      • insert (the last element of c + a) at the end of c
    • otherwise,
      • insert minimum of (the last element of c + a), (c[i - largest[i]] + r) at the end of c
  • return the last element of c

Example

Let us see the following implementation to get better understanding −

def solve(a, r, str):
   size = len(str)
   largest = []
   low = 0
   for upp in range(1, size+1):
      while str[low:upp] not in str[:low]:
         low += 1
      largest.append(upp - low)

   c = [a]
   for i in range(1, size):
      if largest[i] == 0:
         c.append(c[-1] + a)
      else:
         c.append(min(c[-1] + a, c[i - largest[i]] + r))

   return c[-1]

print(solve(5, 4, 'tpoint'))

Input

5, 4, 'tpoint'

Output

29

Updated on: 11-Oct-2021

862 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements