VOOZH about

URL: https://www.geeksforgeeks.org/dsa/zero-one-flip/

⇱ Minimizing the cost to convert A to B with Flips - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimizing the cost to convert A to B with Flips

Last Updated : 23 Jul, 2025

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 8

Input: 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 = 17

Input: 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:

  • Define a recursive function, say solve(idx, flag) to calculate the minimum cost to convert the substring of A starting from index idx to the corresponding substring of B.
  • The flag is true if we have already changed some character before with a cost of y and now, we can change this character without any cost.
  • Maintain a vector v to store all the indices where the character in A differs from B.
  • At any index i, we have 2 choices:
    • Choice 1: Change the current index and the next index by changing adjacent bits starting from v[idx] to v[idx+1] and incurring a cost of (v[idx + 1] - v[idx]) * x
    • Choice 2: Change the current index with cost = y and move to the next index with the advantage of changing any other index in future free of cost.
  • Explore all the choices and return the answer as dp[0][0].

Below is the code for the above approach:


Output
17

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment