Related Articles

# Minimize cost to make all characters of a Binary String equal to ‘1’ by reversing or flipping characters of substrings

• Difficulty Level : Expert
• Last Updated : 22 Jun, 2021

Given a binary string S, and two integers A, which denotes the cost of reversing a substring, and B, which denotes the cost of flipping all characters of a substring, the task is to find the minimum cost to reduce the string S to 1s only.

Examples:

Input: S = “01100”, A = 1, B = 5
Output: 6
Explanation:
One possible way to make all characters equal to ‘1’ is as follows:

1. Reverse the substring {S, S}. Cost = A (= 1), The string modifies to “11000”.
2. Flip the characters of substring {S, S}. Cost of B (= 5). The string modifies to “11111”.

Therefore, the total cost = 5+1 = 6 (which is the minimum cost possible)

Input: S = “1111111”, A = 2, B = 3
Output: 0

Approach: The given problem can be solved based on the following observations:

• Assuming there are P disjoint groups of continuous ‘0’s,
• If A is less than B, then it is optimal to convert P groups into ‘1’ group of continuous ‘0’s by performing the first type of operation for a cost of (P – 1) * A and then converting all the ‘0’s to ‘1’s for a cost of B.
• Otherwise, it is optimal to perform the second operation on each group separately, for a cost of B * P.

Follow the steps below to solve the problem:

• Initialize a variable say P with 0 value to store the count of disjoint groups of continuous 0s.
• Also, initialize a variable say count as 0 to store the temporary count of the number of 0s in a group.
• Iterate over the character of the string S and do the following:
• If the current character is ‘0‘ then increment the count by 1.
• Otherwise, if the count is greater than 0 then increment P by 1 and then assign 0 to count.
• If the count is greater than 0 then increment P by 1.
• Print the minimum cost obtained as (P-1)*A+B.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to calculate minimum cost to``// convert all the characters of S to '1'``void` `MinimumCost(string S, ``int` `A, ``int` `B)``{``    ``// Stores the result``    ``int` `count = 0;` `    ``// Stores the number of groups``    ``// that have 0 as characters``    ``int` `group = 0;` `    ``// Traverse the string S``    ``for` `(``int` `i = 0; i < S.size(); i++) {` `        ``// If current character is '0'``        ``if` `(S[i] == ``'0'``) {``            ``count += 1;``        ``}``        ``else` `{``            ``// If count is greater``            ``// than 0``            ``if` `(count > 0) {``                ``group += 1;``            ``}` `            ``// Set the count to 0``            ``count = 0;``        ``}``    ``}` `    ``// If the last few consecutive``    ``// characters are '0'``    ``if` `(count > 0)``        ``group += 1;` `    ``// If string contains``    ``// all characters as '1'``    ``if` `(group == 0) {``        ``cout << 0 << endl;``    ``}``    ``else` `{``        ``// Minimum Cost``        ``cout << min(A, B) * (group - 1) + B;``    ``}``}` `// Driver Code``int` `main()``{` `    ``// Given Input``    ``int` `A = 1;``    ``int` `B = 5;``    ``string S = ``"01100"``;` `    ``// Function Call``    ``MinimumCost(S, A, B);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``class` `GFG{` `// Function to calculate minimum cost to``// convert all the characters of S to '1'``static` `void` `MinimumCost(String S, ``int` `A, ``int` `B)``{``    ` `    ``// Stores the result``    ``int` `count = ``0``;` `    ``// Stores the number of groups``    ``// that have 0 as characters``    ``int` `group = ``0``;` `    ``// Traverse the string S``    ``for``(``int` `i = ``0``; i < S.length(); i++)``    ``{``        ` `        ``// If current character is '0'``        ``if` `(S.charAt(i) == ``'0'``)``        ``{``            ``count += ``1``;``        ``}``        ``else``        ``{``            ` `            ``// If count is greater``            ``// than 0``            ``if` `(count > ``0``)``            ``{``                ``group += ``1``;``            ``}``            ` `            ``// Set the count to 0``            ``count = ``0``;``        ``}``    ``}` `    ``// If the last few consecutive``    ``// characters are '0'``    ``if` `(count > ``0``)``        ``group += ``1``;` `    ``// If string contains``    ``// all characters as '1'``    ``if` `(group == ``0``)``    ``{``        ``System.out.println(``0``);``    ``}``    ``else``    ``{``        ` `        ``// Minimum Cost``        ``System.out.print(Math.min(A, B) *``                        ``(group - ``1``) + B);``    ``}``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ` `    ``// Given Input``    ``int` `A = ``1``;``    ``int` `B = ``5``;``    ``String S = ``"01100"``;``    ` `    ``// Function Call``    ``MinimumCost(S, A, B);``}``}` `// This code is contributed by SoumikMondal`

## Python3

 `# Python3 program for the above approach` `# Function to calculate minimum cost to``# convert all the characters of S to '1'``def` `MinimumCost(S, A, B):``    ``# Stores the result``    ``count ``=` `0` `    ``# Stores the number of groups``    ``# that have 0 as characters``    ``group ``=` `0` `    ``# Traverse the S``    ``for` `i ``in` `range``(``len``(S)):``        ``# If current character is '0'``        ``if` `(S[i] ``=``=` `'0'``):``            ``count ``+``=` `1``        ``else``:``            ``# If count is greater``            ``# than 0``            ``if` `(count > ``0``):``                ``group ``+``=` `1``            ``# Set the count to 0``            ``count ``=` `0` `    ``# If the last few consecutive``    ``# characters are '0'``    ``if` `(count > ``0``):``        ``group ``+``=` `1` `    ``# If contains``    ``# all characters as '1'``    ``if` `(group ``=``=` `0``):``        ``print``(``0``)``    ``else``:``        ``# Minimum Cost``        ``print``(``min``(A, B) ``*` `(group ``-` `1``) ``+` `B)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:` `    ``# Given Input``    ``A ``=` `1``    ``B ``=` `5``    ``S ``=` `"01100"` `    ``# Function Call``    ``MinimumCost(S, A, B)` `     ``# This code is contributed by mohit kumar 29.`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to calculate minimum cost to``// convert all the characters of S to '1'``static` `void` `MinimumCost(``string` `S, ``int` `A, ``int` `B)``{``    ` `    ``// Stores the result``    ``int` `count = 0;` `    ``// Stores the number of groups``    ``// that have 0 as characters``    ``int` `group` `= 0;` `    ``// Traverse the string S``    ``for``(``int` `i = 0; i < S.Length; i++)``    ``{``        ` `        ``// If current character is '0'``        ``if` `(S[i] == ``'0'``)``        ``{``            ``count += 1;``        ``}``        ``else``        ``{``            ` `            ``// If count is greater``            ``// than 0``            ``if` `(count > 0)``            ``{``                ``group` `+= 1;``            ``}` `            ``// Set the count to 0``            ``count = 0;``        ``}``    ``}` `    ``// If the last few consecutive``    ``// characters are '0'``    ``if` `(count > 0)``        ``group` `+= 1;` `    ``// If string contains``    ``// all characters as '1'``    ``if` `(``group` `== 0)``    ``{``        ``Console.WriteLine(0);``    ``}``    ``else``    ``{``        ` `        ``// Minimum Cost``        ``Console.Write(Math.Min(A, B) *``                      ``(``group` `- 1) + B);``    ``}``}` `// Driver Code``public` `static` `void` `Main()``{``    ` `    ``// Given Input``    ``int` `A = 1;``    ``int` `B = 5;``    ``string` `S = ``"01100"``;` `    ``// Function Call``    ``MinimumCost(S, A, B);``}``}` `// This code is contributed by SURENDRA_GANGWAR`

## Javascript

 ``
Output:
`6`

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up