Skip to content

Commit abf9481

Browse files
authored
Create 2896-apply-operations-to-make-two-strings-equal.js
1 parent 0432065 commit abf9481

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {string} s1
3+
* @param {string} s2
4+
* @param {number} x
5+
* @return {number}
6+
*/
7+
const minOperations = function(s1, s2, x) {
8+
const diffs = [];
9+
for (let i = 0; i < s1.length; i++) {
10+
if (s1[i] !== s2[i]) {
11+
diffs.push(i);
12+
}
13+
}
14+
15+
if (diffs.length % 2 === 1) {
16+
return -1;
17+
}
18+
19+
const cache = new Map();
20+
function bestCostUpTo(i) {
21+
if (i === 0) {
22+
return x / 2;
23+
}
24+
if (i === -1) {
25+
return 0;
26+
}
27+
if (cache.has(i)) {
28+
return cache.get(i);
29+
}
30+
const cost = Math.min(
31+
bestCostUpTo(i - 1) + x / 2,
32+
bestCostUpTo(i - 2) + diffs[i] - diffs[i - 1]
33+
);
34+
cache.set(i, cost);
35+
return cost;
36+
}
37+
38+
return Math.floor(bestCostUpTo(diffs.length - 1));
39+
};

0 commit comments

Comments
 (0)