![]() |
VOOZH | about |
Given two binary strings A and B both of the same length and two integers x and y. In one operation, we can select two indices l and r and flip the number at A[l] and A[r] i.e. 1 to 0 and 0 to 1. If l+1 = r, the cost of this operation is x, otherwise the cost is y. The task is to find the minimum cost to convert A to B by applying the above operations or print -1 if it is impossible to do so.
Examples:
Input: A = "01001", B = "00101", x = 8, y = 9
Output: 8
Explanation: select indices 1 and 2 and apply the operation which costs 8Input: A = "10000011000001", B = "00000000000000", x = 8, y = 9
Output: 17
Explanation: Select indices 6 and 7 and apply the operation, so cost = 8 and select index 0 and 13 and apply the operation with cost = 9. So total cost = 8 + 9 = 17Input: A = "01000", B = "11011", x = 7, y = 2
Output: -1
Explanation: It is impossible to convert string a to b
Approach: To solve the problem, follow the below idea:
The approach is to use Dynamic programming to find the minimum cost of converting string a to string b by applying the specified operations.
Steps to solve the problem:
Below is the code for the above approach:
17
Time Complexity: O(N)
Auxiliary Space: O(N)