Suppose we have a binary string s and two values zero_one and one_zero. Now let us consider an operation where we can delete any substring "01" and receive zero_one points. Or we can remove any substring "10" and receive one_zero points. We have to find the maximum number of points we can get after any number of operations.
So, if the input is like s = "10100101" zero_one = 3 one_zero = 2, then the output will be 11, as we can remove "01" three times to get 3*3 = 9 points. Then the remaining string is 10. By removing this we can get another 2 points so the total is 11.
To solve this, we will follow these steps −
A := a list of bits given as input string
if zero_one < one_zero, then
swap zero_one and one_zero
for i in range 0 to size of A, do
A[i] := A[i] XOR 1
ans := 0
stack := a new stack
for each x in A, do
if stack is not empty and stack top element < x, then
pop from stack
ans := ans + zero_one
otherwise,
push x into stack
ans := ans + one_zero * minimum of occurrence of 0 in stack and occurrence of 1 in stack
return ans
Example (Python)
Let us see the following implementation to get a better understanding −
class Solution: def solve(self, S, zero_one, one_zero): A = list(map(int, S)) if zero_one < one_zero: zero_one, one_zero = one_zero, zero_one for i in range(len(A)): A[i] ^= 1 ans = 0 stack = [] for x in A: if stack and stack[-1] < x: stack.pop() ans += zero_one else: stack.append(x) ans += one_zero * min(stack.count(0), stack.count(1)) return ans ob = Solution() s = "10100101" zero_one = 3 one_zero = 2 print(ob.solve(s, zero_one, one_zero))
Input
"10100101", 3, 2
Output
11