Saturday, December 28, 2024
Google search engine
HomeData Modelling & AIMinimum Cost to make two Numeric Strings Identical

Minimum Cost to make two Numeric Strings Identical

Given two numeric strings, A and B. A numeric string is a string that contains only digits [‘0’-‘9’].
The task is to make both the strings equal in minimum cost. The only operation that you are allowed to do is to delete a character (i.e. digit) from any of the strings (A or B). The cost of deleting a digit D is D units.

Examples

Input : A = “7135”, B = “135” 
Output : 7 
To make both string identical we have to delete ‘7’ from string A.

Input : A = “9142”, B = “1429” 
Output : 14 
There are 2 ways to make string “9142” identical to “1429” i.e either by deleting ‘9’ from both the strings or by deleting ‘1’, ‘4’and ‘2’ from both the string. Deleting 142 from both the string will cost 2*(1+4+2)=14 which is more optimal than deleting ‘9’. 

This problem is a variation of a popular Dynamic Programming problem – Longest Common Subsequence. The idea is to find the maximum weight common subsequence which will be our required optimal identical string. To find the cost of deletion, subtract the sum of maximum weight common subsequence from the sum of string A and B.

Minimum weight to make string identical = costA + costB – 2*(cost of LCS)

Implementation:

C++




// CPP program to find minimum cost to make
// two numeric strings identical
 
#include <bits/stdc++.h>
 
using namespace std;
 
typedef long long int ll;
 
// Function to find weight of LCS
int lcs(int dp[101][101], string a, string b,
        int m, int n)
{
    for (int i = 0; i < 100; i++)
        for (int j = 0; j < 100; j++)
            dp[i][j] = -1;
 
    if (m < 0 || n < 0) {
        return 0;
    }
 
    // if this state is already
    // calculated then return
    if (dp[m][n] != -1)
        return dp[m][n];
 
    int ans = 0;
    if (a[m] == b[n]) {
        // adding required weight for
        // particular match
        ans = int(a[m] - 48) + lcs(dp, a, b,
                                   m - 1, n - 1);
    }
    else
        // recurse for left and right child
        // and store the max
        ans = max(lcs(dp, a, b, m - 1, n),
                  lcs(dp, a, b, m, n - 1));
 
    dp[m][n] = ans;
    return ans;
}
 
// Function to calculate cost of string
int costOfString(string str)
{
    int cost = 0;
 
    for (int i = 0; i < str.length(); i++)
        cost += int(str[i] - 48);
 
    return cost;
}
 
// Driver code
int main()
{
    string a, b;
 
    a = "9142";
    b = "1429";
 
    int dp[101][101];
 
    // Minimum cost needed to make two strings identical
    cout << (costOfString(a) + costOfString(b) -
                       2 * lcs(dp, a, b, a.length() - 1,
                                       b.length() - 1));
 
    return 0;
}


Java




// Java program to find minimum cost to make
// two numeric strings identical
 
import java.io.*;
 
class GFG {
  
 
// Function to find weight of LCS
 static int lcs(int dp[][], String a, String b,
        int m, int n)
{
    for (int i = 0; i < 100; i++)
        for (int j = 0; j < 100; j++)
            dp[i][j] = -1;
 
    if (m < 0 || n < 0) {
        return 0;
    }
 
    // if this state is already
    // calculated then return
    if (dp[m][n] != -1)
        return dp[m][n];
 
    int ans = 0;
    if (a.charAt(m) == b.charAt(n)) {
        // adding required weight for
        // particular match
        ans = (a.charAt(m) - 48) + lcs(dp, a, b,
                                m - 1, n - 1);
    }
    else
        // recurse for left and right child
        // and store the max
        ans = Math.max(lcs(dp, a, b, m - 1, n),
                lcs(dp, a, b, m, n - 1));
 
    dp[m][n] = ans;
    return ans;
}
 
// Function to calculate cost of string
 static int costOfString(String str)
{
    int cost = 0;
 
    for (int i = 0; i < str.length(); i++)
        cost += (str.charAt(i) - 48);
 
    return cost;
}
 
// Driver code
    public static void main (String[] args) {
            String a, b;
 
    a = "9142";
    b = "1429";
 
    int dp[][] = new int[101][101];
 
    // Minimum cost needed to make two strings identical
    System.out.print( (costOfString(a) + costOfString(b) -
                    2 * lcs(dp, a, b, a.length() - 1,
                                    b.length() - 1)));
 
    }
}
// This code is contributed by anuj_67.


Python 3




# Python 3 program to find minimum cost
# to make two numeric strings identical
 
# Function to find weight of LCS
def lcs(dp, a, b, m, n):
 
    for i in range(100):
        for j in range(100):
            dp[i][j] = -1
 
    if (m < 0 or n < 0) :
        return 0
 
    # if this state is already calculated
    # then return
    if (dp[m][n] != -1):
        return dp[m][n]
 
    ans = 0
    if (a[m] == b[n]):
         
        # adding required weight for
        # particular match
        ans = (ord(a[m]) - 48) + lcs(dp, a, b,
                                     m - 1, n - 1)
     
    else:
         
        # recurse for left and right child
        # and store the max
        ans = max(lcs(dp, a, b, m - 1, n),
                  lcs(dp, a, b, m, n - 1))
 
    dp[m][n] = ans
    return ans
 
# Function to calculate cost of string
def costOfString(s):
     
    cost = 0
 
    for i in range(len(s)):
        cost += (ord(s[i]) - 48)
 
    return cost
 
# Driver code
if __name__ == "__main__":
 
    a = "9142"
    b = "1429"
 
    dp = [[0 for x in range(101)]
             for y in range(101)]
 
    # Minimum cost needed to make two
    # strings identical
    print(costOfString(a) + costOfString(b) - 2 *
           lcs(dp, a, b, len(a) - 1, len(b) - 1))
 
# This code is contributed by ita_c


C#




// C# program to find minimum cost to make
// two numeric strings identical
using System;
public class GFG {
 
// Function to find weight of LCS
static int lcs(int [,]dp, String a, String b,
        int m, int n)
{
    for (int i = 0; i < 100; i++)
        for (int j = 0; j < 100; j++)
            dp[i,j] = -1;
 
    if (m < 0 || n < 0) {
        return 0;
    }
 
    // if this state is already
    // calculated then return
    if (dp[m,n] != -1)
        return dp[m,n];
 
    int ans = 0;
    if (a[m] == b[n]) {
        // adding required weight for
        // particular match
        ans = (a[m] - 48) + lcs(dp, a, b, m - 1, n - 1);
    }
    else
        // recurse for left and right child
        // and store the max
        ans = Math.Max(lcs(dp, a, b, m - 1, n),
                lcs(dp, a, b, m, n - 1));
 
    dp[m,n] = ans;
    return ans;
}
 
// Function to calculate cost of string
static int costOfString(String str)
{
    int cost = 0;
 
    for (int i = 0; i < str.Length; i++)
        cost += (str[i] - 48);
 
    return cost;
}
 
// Driver code
    public static void Main () {
            String a, b;
 
    a = "9142";
    b = "1429";
 
    int [,]dp = new int[101,101];
 
    // Minimum cost needed to make two strings identical
    Console.Write( (costOfString(a) + costOfString(b) -
                2 * lcs(dp, a, b, a.Length- 1,
                b.Length - 1)));
 
    }
}
// This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript program to find minimum cost to make
// two numeric strings identical
     
    // Function to find weight of LCS
    function lcs(dp,a,b,m,n)
    {
         
   
    if (m < 0 || n < 0) {
        return 0;
    }
   
    // if this state is already
    // calculated then return
    if (dp[m][n] != -1)
        return dp[m][n];
   
    let ans = 0;
    if (a[m] == b[n]) {
        // adding required weight for
        // particular match
        ans = (a[m].charCodeAt(0) - 48) + lcs(dp, a, b,
                                m - 1, n - 1);
    }
    else
        // recurse for left and right child
        // and store the max
        ans = Math.max(lcs(dp, a, b, m - 1, n),
                lcs(dp, a, b, m, n - 1));
   
    dp[m][n] = ans;
    return ans;
    }
     
    // Function to calculate cost of string
    function costOfString(str)
    {
        let cost = 0;
   
    for (let i = 0; i < str.length; i++)
        cost += (str[i].charCodeAt(0) - 48);
   
    return cost;
    }
     
    // Driver code
    let a = "9142";
    let b = "1429";
    let dp=new Array(101);
    for(let i=0;i<dp.length;i++)
    {
        dp[i]=new Array(101);
        for(let j=0;j<101;j++)
        {
            dp[i][j]=-1;
        }
    }
    // Minimum cost needed to make two strings identical
    document.write( (costOfString(a) + costOfString(b) -
                    2 * lcs(dp, a, b, a.length - 1,
                                    b.length - 1)));
     
    // This code is contributed by avanitrachhadiya2155
</script>


Output

14
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!

RELATED ARTICLES

Most Popular

Recent Comments