![]() |
VOOZH | about |
Given two strings A of length N and B of length M. These strings contain lowercase English alphabets. You are also given an integer K. You can change the character of x of string A to any other character y. The cost of this conversion is abs(ASCII(x)- ASCII(y)). Find the minimum cost required such that the length of the Longest Common Subsequence (LCS) of A and B is at least K.
Constraints:
Examples:
Input: N = 5, M = 4, K = 3, A = "abcba", B = "acyx"
Output: 22
Explanation: As the minimum length of the subsequences is 3, we have to match any 3 characters of A with B. We can convert A[3] to "x" with cost = 22, then we can get the Longest Common Subsequence as "acx" of length 3.Input: N = 3, M = 3, K = 3, A = "abc", B = "abc"
Output: 0
Explanation: As the minimum length is 3 both the string is of length 3 and every character is matches no change is needed and the minimum cost will be 0.
Approach: To solve the problem follow the below idea
The problem can be solved using Dynamic Programming. We can make a recursive function rec(i1, i2, K) which returns the minimum cost to have a Longest Common Subsequence of length K if we are at index i1 in string A and index i2 in string B. For any function rec(i1, i2, K) we have 3 choices:
- Skip the i1th character of A, cost = rec(i1 - 1, i2, K)
- Skip the i2th character of B, cost = rec(i1, i2 - 1, K)
- Include the i1th character of A and i2th character of B for LCS with cost = abs(A[i1] - B[i2]) + rec(i1 - 1, i2 - 1, K - 1)
Use a 3D array dp[N][M][K] for memoization. Iterate for each N, M and K get the minimum cost.
Below are the steps to solve this problem:
Below is the implementation of the code:
22
Time Complexity: O(N * M * K), where N is the length of string A and M is the length of string B.
Auxiliary Space: O(N * M * K)