Saturday, July 6, 2024
HomeData ModellingData Structure & AlgorithmMinimum cost to make Longest Common Subsequence of length k

Minimum cost to make Longest Common Subsequence of length k

Given two string X, Y and an integer k. Now the task is to convert string X with the minimum cost such that the Longest Common Subsequence of X and Y after conversion is of length k. The cost of conversion is calculated as XOR of old character value and new character value. The character value of ‘a’ is 0, ‘b’ is 1, and so on.

Examples: 

Input : X = "abble", 
        Y = "pie",
        k = 2
Output : 25

If you changed 'a' to 'z', it will cost 0 XOR 25.

The problem can be solved by slight change in Dynamic Programming problem of Longest Increasing Subsequence. Instead of two states, we maintain three states. 
Note, that if k > min(n, m) then it’s impossible to attain LCS of atleast k length, else it’s always possible. 
Let dp[i][j][p] stores the minimum cost to achieve LCS of length p in x[0…i] and y[0….j]. 
With base step as dp[i][j][0] = 0 because we can achieve LCS of 0 length without any cost and for i < 0 or j 0 in such case). 
Else there are 3 cases: 
1. Convert x[i] to y[j]. 
2. Skip ith character from x. 
3. Skip jth character from y.

If we convert x[i] to y[j], then cost = f(x[i]) XOR f(y[j]) will be added and LCS will decrease by 1. f(x) will return the character value of x. 
Note that the minimum cost to convert a character ‘a’ to any character ‘c’ is always f(a) XOR f(c) because f(a) XOR f(c) <= (f(a) XOR f(b) + f(b) XOR f(c)) for all a, b, c. 
If you skip ith character from x then i will be decreased by 1, no cost will be added and LCS will remain the same. 
If you skip jth character from x then j will be decreased by 1, no cost will be added and LCS will remain the same.

Therefore,

dp[i][j][k] = min(cost + dp[i - 1][j - 1][k - 1], 
                  dp[i - 1][j][k], 
                  dp[i][j - 1][k])
The minimum cost to make the length of their
LCS atleast k is dp[n - 1][m - 1][k]

C++




#include <bits/stdc++.h>
using namespace std;
const int N = 30;
 
// Return Minimum cost to make LCS of length k
int solve(char X[], char Y[], int l, int r,
                     int k, int dp[][N][N])
{
    // If k is 0.
    if (!k)
        return 0;
 
    // If length become less than 0, return
    // big number.
    if (l < 0 | r < 0)
        return 1e9;
 
    // If state already calculated.
    if (dp[l][r][k] != -1)
        return dp[l][r][k];
 
    // Finding the cost
    int cost = (X[l] - 'a') ^ (Y[r] - 'a');
 
    // Finding minimum cost and saving the state value
    return dp[l][r][k] = min({cost +
                      solve(X, Y, l - 1, r - 1, k - 1, dp),
                             solve(X, Y, l - 1, r, k, dp),
                             solve(X, Y, l, r - 1, k, dp)});
}
 
// Driven Program
int main()
{
    char X[] = "abble";
    char Y[] = "pie";
    int n = strlen(X);
    int m = strlen(Y);
    int k = 2;
 
    int dp[N][N][N];
    memset(dp, -1, sizeof dp);
    int ans = solve(X, Y, n - 1, m - 1, k, dp);
 
    cout << (ans == 1e9 ? -1 : ans) << endl;
    return 0;
}


Java




import java.util.*;
import java.io.*;
 
class GFG
{
 
    static int N = 30;
 
    // Return Minimum cost to make LCS of length k
    static int solve(char X[], char Y[], int l, int r,
                                    int k, int dp[][][])
    {
        // If k is 0.
        if (k == 0)
        {
            return 0;
        }
 
        // If length become less than 0, return
        // big number.
        if (l < 0 | r < 0)
        {
            return (int) 1e9;
        }
 
        // If state already calculated.
        if (dp[l][r][k] != -1)
        {
            return dp[l][r][k];
        }
 
        // Finding the cost
        int cost = (X[l] - 'a') ^ (Y[r] - 'a');
 
        // Finding minimum cost and saving the state value
        return dp[l][r][k] = Math.min(Math.min(cost +
                solve(X, Y, l - 1, r - 1, k - 1, dp),
                solve(X, Y, l - 1, r, k, dp)),
                solve(X, Y, l, r - 1, k, dp));
    }
 
    // Driver code
    public static void main(String[] args)
    {
        char X[] = "abble".toCharArray();
        char Y[] = "pie".toCharArray();
        int n = X.length;
        int m = Y.length;
        int k = 2;
 
        int[][][] dp = new int[N][N][N];
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                for (int l = 0; l < N; l++)
                {
                    dp[i][j][l] = -1;
                }
            }
        }
        int ans = solve(X, Y, n - 1, m - 1, k, dp);
 
        System.out.println(ans == 1e9 ? -1 : ans);
    }
}
 
// This code contributed by Rajput-Ji


Python3




# Python3 program to calculate Minimum cost
# to make Longest Common Subsequence of length k
N = 30
 
# Return Minimum cost to make LCS of length k
def solve(X, Y, l, r, k, dp):
 
    # If k is 0
    if k == 0:
        return 0
 
    # If length become less than 0,
    # return big number
    if l < 0 or r < 0:
        return 1000000000
 
    # If state already calculated
    if dp[l][r][k] != -1:
        return dp[l][r][k]
 
    # Finding cost
    cost = ((ord(X[l]) - ord('a')) ^
            (ord(Y[r]) - ord('a')))
 
    dp[l][r][k] = min([cost + solve(X, Y, l - 1,
                                          r - 1, k - 1, dp),
                              solve(X, Y, l - 1, r, k, dp),
                              solve(X, Y, l, r - 1, k, dp)])
 
    return dp[l][r][k]
 
# Driver Code
if __name__ == "__main__":
    X = "abble"
    Y = "pie"
    n = len(X)
    m = len(Y)
    k = 2
    dp = [[[-1] * N for __ in range(N)]
                    for ___ in range(N)]
    ans = solve(X, Y, n - 1, m - 1, k, dp)
 
    print(-1 if ans == 1000000000 else ans)
 
# This code is contributed
# by vibhu4agarwal


C#




// C# program to find subarray with
// sum closest to 0
using System;
     
class GFG
{
 
    static int N = 30;
 
    // Return Minimum cost to make LCS of length k
    static int solve(char []X, char []Y, int l, int r,
                                    int k, int [,,]dp)
    {
        // If k is 0.
        if (k == 0)
        {
            return 0;
        }
 
        // If length become less than 0, return
        // big number.
        if (l < 0 | r < 0)
        {
            return (int) 1e9;
        }
 
        // If state already calculated.
        if (dp[l,r,k] != -1)
        {
            return dp[l,r,k];
        }
 
        // Finding the cost
        int cost = (X[l] - 'a') ^ (Y[r] - 'a');
 
        // Finding minimum cost and saving the state value
        return dp[l,r,k] = Math.Min(Math.Min(cost +
                solve(X, Y, l - 1, r - 1, k - 1, dp),
                solve(X, Y, l - 1, r, k, dp)),
                solve(X, Y, l, r - 1, k, dp));
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        char []X = "abble".ToCharArray();
        char []Y = "pie".ToCharArray();
        int n = X.Length;
        int m = Y.Length;
        int k = 2;
 
        int[,,] dp = new int[N, N, N];
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                for (int l = 0; l < N; l++)
                {
                    dp[i,j,l] = -1;
                }
            }
        }
        int ans = solve(X, Y, n - 1, m - 1, k, dp);
 
        Console.WriteLine(ans == 1e9 ? -1 : ans);
    }
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// JavaScript program to calculate Minimum cost
// to make Longest Common Subsequence of length k
const N = 30
 
// Return Minimum cost to make LCS of length k
function solve(X, Y, l, r, k, dp){
 
    // If k is 0
    if(k == 0)
        return 0
 
    // If length become less than 0,
    // return big number
    if(l < 0 || r < 0)
        return 1000000000
 
    // If state already calculated
    if(dp[l][r][k] != -1)
        return dp[l][r][k]
 
    // Finding cost
    let cost = ((X[l].charCodeAt(0) - 'a'.charCodeAt(0)) ^ (Y[r].charCodeAt(0) - 'a'.charCodeAt(0)))
 
    dp[l][r][k] = Math.min(Math.min(cost + solve(X, Y, l - 1, r - 1, k - 1, dp),solve(X, Y, l - 1, r, k, dp)),
                              solve(X, Y, l, r - 1, k, dp))
 
    return dp[l][r][k]
}
 
// Driver Code
 
let X = "abble"
let Y = "pie"
let n = X.length
let m = Y.length
let k = 2
let dp = new Array(N);
for(let i = 0; i < N; i++)
{
    dp[i] = new Array(N);
    for(let j = 0; j < N; j++)
    {
        dp[i][j] = new Array(N).fill(-1);
    }
}
let ans = solve(X, Y, n - 1, m - 1, k, dp)
 
document.write((ans == 1000000000)? -1:ans)
 
// This code is contributed by shinjanpatra
 
</script>


Output

3

Time Complexity: O(n3)
Auxiliary Space: O(n3)

Efficient approach: Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a 3d DP to store the solution of the subproblems.
  • Initialize the DP with base cases when k= 0 dp value is 0 and when n=0 or m=0 dp value is 1e9 and dp[0][0][0] = 0 .
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
  • Return the final solution stored in dp[n][m][k].

Implementation :

C++




// C++ code for above approach
 
#include <bits/stdc++.h>
using namespace std;
const int N = 30;
 
// Return Minimum cost to make LCS of length k
int solve(char X[], char Y[], int n, int m, int k)
{
    // Create 3D DP
    int dp[n + 1][m + 1][k + 1];
 
    // initialize DP with base cases
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            for (int p = 0; p <= k; p++) {
                if (k == 0) {
                    dp[i][j][p] = 0;
                }
                else if (i == 0 || j == 0) {
                    dp[i][j][p] = 1e9;
                }
            }
        }
    }
 
    dp[0][0][0] = 0;
 
    // iterate over subproblem to get the current
    // value from previous computation store in DP
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            for (int p = 1; p <= k; p++) {
                int cost
                    = (X[i - 1] - 'a') ^ (Y[j - 1] - 'a');
 
                // update DP
                dp[i][j][p] = min(
                    { cost + dp[i - 1][j - 1][p - 1],
                      dp[i - 1][j][p], dp[i][j - 1][p] });
            }
        }
    }
 
    // return final answer
    return dp[n][m][k];
}
 
// Driven Program
int main()
{
    char X[] = "abble";
    char Y[] = "pie";
    int n = strlen(X);
    int m = strlen(Y);
    int k = 2;
 
    // function call
    int ans = solve(X, Y, n, m, k);
 
    cout << (ans == 1e9 ? -1 : ans) << endl;
    return 0;
}


Python3




INF = float('inf')
 
# Return Minimum cost to make LCS of length k
 
 
def solve(X, Y, n, m, k):
    # Create 3D DP
    dp = [[[0 for p in range(k+1)] for j in range(m+1)] for i in range(n+1)]
 
    # initialize DP with base cases
    for i in range(n+1):
        for j in range(m+1):
            for p in range(k+1):
                if k == 0:
                    dp[i][j][p] = 0
                elif i == 0 or j == 0:
                    dp[i][j][p] = INF
 
    dp[0][0][0] = 0
 
    # iterate over subproblem to get the current
    # value from previous computation store in DP
    for i in range(1, n+1):
        for j in range(1, m+1):
            for p in range(1, k+1):
                cost = ord(X[i-1]) - ord('a') ^ ord(Y[j-1]) - ord('a')
 
                # update DP
                dp[i][j][p] = min(cost + dp[i-1][j-1][p-1],
                                  dp[i-1][j][p], dp[i][j-1][p])
 
    # return final answer
    return -1 if dp[n][m][k] == INF else dp[n][m][k]
 
 
# Driven Program
if __name__ == '__main__':
    X = "abble"
    Y = "pie"
    n = len(X)
    m = len(Y)
    k = 2
 
    # function call
    ans = solve(X, Y, n, m, k)
 
    print(ans)


Javascript




const N = 30;
 
// Return Minimum cost to make LCS of length k
function solve(X, Y, n, m, k) {
    // Create 3D DP
    const dp = new Array(n + 1).fill(null)
        .map(() => new Array(m + 1).fill(null)
            .map(() => new Array(k + 1).fill(0)));
 
    // initialize DP with base cases
    for (let i = 0; i <= n; i++) {
        for (let j = 0; j <= m; j++) {
            for (let p = 0; p <= k; p++) {
                if (k === 0) {
                    dp[i][j][p] = 0;
                } else if (i === 0 || j === 0) {
                    dp[i][j][p] = Infinity;
                }
            }
        }
    }
 
    dp[0][0][0] = 0;
 
    // iterate over subproblem to get the current
    // value from previous computation store in DP
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= m; j++) {
            for (let p = 1; p <= k; p++) {
                const cost = (X[i - 1].charCodeAt() - 'a'.charCodeAt()) ^
                    (Y[j - 1].charCodeAt() - 'a'.charCodeAt());
 
                // update DP
                dp[i][j][p] = Math.min(
                    cost + dp[i - 1][j - 1][p - 1],
                    dp[i - 1][j][p],
                    dp[i][j - 1][p]);
            }
        }
    }
 
    // return final answer
    return dp[n][m][k];
}
 
// Driven Program
const X = "abble";
const Y = "pie";
const n = X.length;
const m = Y.length;
const k = 2;
 
// function call
const ans = solve(X, Y, n, m, k);
 
console.log(ans === Infinity ? -1 : ans);


Output

3

Time Complexity: O(n*m*k)
Auxiliary Space: O(n*m*k)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments