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)

Below is the implementation of the above idea:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 

chevron_right


Output:

14


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : vt_m, Rajput-Ji, chitranayal