Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to determine the minimum cost to build a given string in python
Suppose we have to build a string str of length n. To build the string, we can perform two operations:
- Add a character to the end of str for cost a
- Add a substring that already exists in the current string for cost r
We need to calculate the minimum cost of building the string str using dynamic programming.
Example
If the input is a = 5, r = 4, str = 'tpoint', then the output will be 29.
To build the string 'tpoint', the cost breakdown is:
str = 't'; new character added, cost = 5 str = 'tp'; new character added, cost = 5 str = 'tpo'; new character added, cost = 5 str = 'tpoi'; new character added, cost = 5 str = 'tpoin'; new character added, cost = 5 str = 'tpoint'; substring 't' copied, cost = 4
Total cost: 5 + 5 + 5 + 5 + 5 + 4 = 29
Algorithm
The approach follows these steps:
- Find the longest substring ending at each position that exists earlier in the string
- Use dynamic programming to calculate minimum cost at each position
- Choose between adding a new character (cost a) or copying a substring (cost r)
Implementation
def solve(a, r, string):
size = len(string)
largest = []
low = 0
# Find longest matching substring for each position
for upp in range(1, size + 1):
while string[low:upp] not in string[:low]:
low += 1
largest.append(upp - low)
# Dynamic programming to find minimum cost
cost = [a] # Cost to build first character
for i in range(1, size):
if largest[i] == 0:
# No matching substring, must add new character
cost.append(cost[-1] + a)
else:
# Choose minimum between adding character or copying substring
add_char = cost[-1] + a
copy_substring = cost[i - largest[i]] + r
cost.append(min(add_char, copy_substring))
return cost[-1]
# Test the function
result = solve(5, 4, 'tpoint')
print(f"Minimum cost to build 'tpoint': {result}")
The output of the above code is:
Minimum cost to build 'tpoint': 29
How It Works
The algorithm works in two phases:
- Phase 1: For each position, find the longest substring ending at that position which already exists earlier in the string
-
Phase 2: Use dynamic programming where
cost[i]represents the minimum cost to build the string up to position i
At each position, we choose the minimum between:
- Adding a new character:
cost[i-1] + a - Copying a substring:
cost[i-length] + r
Conclusion
This dynamic programming approach efficiently finds the minimum cost to build a string by choosing between adding new characters or reusing existing substrings. The time complexity is O(n³) due to substring operations.
