
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Digit Sum of Deleted Digits in Python
Suppose we have two strings s and t of digits, we have to find a way to remove digits in the strings so that: 1. Two strings are same 2. The sum of the digits that are deleted is minimized Finally return the minimized sum.
So, if the input is like s = "41272" t = "172", then the output will be 6, as we can remove "4" and "2" from the first string to get "172".
To solve this, we will follow these steps −
Define a function lcs() . This will take a, b, m, n
table := a 2d matrix of size (n + 1) x (m + 1) and fill with 0
-
for i in range 1 to m, do
-
for j in range 1 to n, do
-
if a[i - 1] is same as b[j - 1], then
table[i, j] := table[i - 1, j - 1] + 2 *(ASCII of a[i - 1] - 48)
-
otherwise,
table[i, j] = maximum of table[i - 1, j] and table[i, j - 1])
-
-
return table[m, n]
From the main method do the following
m := size of a, n := size of b
c := 0
-
for i in range 0 to m, do
c := c + ASCII of a[i] - 48
-
for i in range 0 to n, do
c := c + ASCII of b[i] - 48
result := c - lcs(a, b, m, n)
return result
Example (Python)
Let us see the following implementation to get better understanding −
class Solution: def lcs(self, a, b, m, n): table = [[0 for i in range(n + 1)] for j in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: table[i][j] = table[i - 1][j - 1] + 2 * (ord(a[i - 1]) - 48) else: table[i][j] = max(table[i - 1][j], table[i][j - 1]) return table[m][n] def solve(self, a, b): m = len(a) n = len(b) c = 0 for i in range(m): c += ord(a[i]) - 48 for i in range(n): c += ord(b[i]) - 48 result = c - self.lcs(a, b, m, n) return result ob = Solution() s = "41272" t = "172" print(ob.solve(s, t))
Input
"41272", "172"
Output
6