# C++ program to find minimum how many coins needed to buy binary string

Suppose we have three numbers c0, c1 and h, and a binary string S. We can flip any bit in S. We should pay h coins for each change. After some changes (possibly zero) we want to buy the string. To buy the string we should buy all its characters. To buy the bit 0 we should pay c0 coins, to buy the bit 1 you should pay c1 coins. We have to find the minimum number of coins needed to buy the string.

So, if the input is like c0 = 10; c1 = 100; h = 1; S = "01010", then the output will be 52, because firstly we change 2nd and 4th bits in S and pay 2 coins for that. Now the string will be 00000. After that, we can buy the string and pay 5⋅10=50 coins for that. The total number of coins paid will be 2+50=52.

## Steps

To solve this, we will follow these steps −

k := 0
n := size of S
for initialize i := 0, when i < n, update (increase i by 1), do:
if S[i] is same as '0', then:
k := k + minimum of c0 and (c1 + h)
Otherwise
k := k + minimum of (c0 + h) and c1
return k

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int c0, int c1, int h, string S) {
int k = 0;
int n = S.size();
for (int i = 0; i < n; i++) {
if (S[i] == '0')
k = k + min(c0, c1 + h);
else
k = k + min(c0 + h, c1);
}
return k;
}
int main() {
int c0 = 10;
int c1 = 100;
int h = 1;
string S = "01010";
cout << solve(c0, c1, h, S) << endl;
}

## Input

10, 100, 1, "01010"

## Output

52