Input: s1 ="1100011000", s2 ="0101001010", x =2Output: 4Explanation: We can do the following operations:- Choose i =3 and apply the second operation. The resulting string is s1 ="110 _**11**_ 11000".- Choose i =4 and apply the second operation. The resulting string is s1 ="1101** _00_** 1000".- Choose i =0 and j =8 and apply the first operation. The resulting string is s1 ="_**0**_ 1010010 _**1**_ 0"= s2.The total cost is1+1+2=4. It can be shown that it is the minimum cost possible.
The key idea is to minimize the cost by pairing adjacent mismatches with the cheaper operation (cost 1), and use the more expensive operation (cost x) for remaining unpaired mismatches. If the number of mismatches is odd, it’s impossible.
classSolution {
public:int minOperations(string s1, string s2, int x) {
int n = s1.size();
vector<int> diff;
for (int i =0; i < n; ++i)
if (s1[i] != s2[i]) diff.push_back(i);
int m = diff.size();
if (m %2) return-1;
vector<int> dp(m +1, 1e9);
dp[0] =0;
for (int i =2; i <= m; ++i) {
// Pair last two mismatches
int cost = (diff[i-1] == diff[i-2] +1) ? min(x, 1) : x;
dp[i] = min(dp[i], dp[i-2] + cost);
}
return dp[m];
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
publicintminOperations(String s1, String s2, int x) {
int n = s1.length();
List<Integer> diff =new ArrayList<>();
for (int i = 0; i < n; ++i)
if (s1.charAt(i) != s2.charAt(i)) diff.add(i);
int m = diff.size();
if (m % 2 != 0) return-1;
int[] dp =newint[m + 1];
Arrays.fill(dp, Integer.MAX_VALUE/ 2);
dp[0]= 0;
for (int i = 2; i <= m; ++i) {
int cost = (diff.get(i-1) == diff.get(i-2) + 1) ? Math.min(x, 1) : x;
dp[i]= Math.min(dp[i], dp[i-2]+ cost);
}
return dp[m];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defminOperations(self, s1: str, s2: str, x: int) -> int:
n = len(s1)
diff = [i for i in range(n) if s1[i] != s2[i]]
m = len(diff)
if m %2:
return-1 dp = [float('inf')] * (m +1)
dp[0] =0for i in range(2, m +1):
cost = x
if diff[i-1] == diff[i-2] +1:
cost = min(x, 1)
dp[i] = min(dp[i], dp[i-2] + cost)
return dp[m]