Description
Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat" Output: 231 Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. Deleting "t" from "eat" adds 116 to the sum. At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
Input: s1 = "delete", s2 = "leet" Output: 403 Explanation: Deleting "dee" from "delete" to turn the string into "let", adds 100[d] + 101[e] + 101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Constraints:
1 <= s1.length, s2.length <= 1000s1ands2consist of lowercase English letters.
Solutions
This function solves the problem of making two strings equal by deleting characters, while minimizing the total ASCII value of everything deleted. Instead of tracking deletions directly, it flips the problem around: it uses dynamic programming to find the common subsequence with the maximum possible ASCII sum — the characters worth keeping. The 2D table dp[i+1][j+1] stores the best ASCII sum of a common subsequence using the first i characters of s1 and the first j characters of s2: when characters match (s1[i] === s2[j]), it extends the previous best with that character's ASCII value via dp[i][j] + s1.charCodeAt(i); otherwise it carries forward the larger of the two neighboring results with Math.max. Finally, it sums the ASCII values of every character in both strings into total, and returns total - 2 * dp[m][n] — subtracting the kept subsequence twice because those characters survive in both strings, leaving exactly the ASCII sum of the deleted characters.
/**
* @param {string} s1
* @param {string} s2
* @return {number}
*/
var minimumDeleteSum = function (s1, s2) {
const m = s1.length;
const n = s2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (s1[i] === s2[j]) {
dp[i + 1][j + 1] = dp[i][j] + s1.charCodeAt(i);
} else {
dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
}
}
}
let total = 0;
for (let i = 0; i < m; i++) {
total += s1.charCodeAt(i);
}
for (let i = 0; i < n; i++) {
total += s2.charCodeAt(i);
}
return total - 2 * dp[m][n];
};