- Related Questions & Answers
- Deletions of “01” or “10” in binary string to make it free from “01” or “10” in C++ Program
- Deletions of “01” or “10” in binary string to make it free from “01” or “10" in C++?
- Find longest palindrome formed by removing or shuffling chars from string in Python
- Find longest palindrome formed by removing or shuffling chars from string in C++
- How can we get substring from a string in Python?
- Program to find maximum credit we can get by finishing some assignments in python
- Program to find maximum additive score by deleting numbers in Python
- How to get max alphabetical character from the string in Python?
- Program to find maximum sum by removing K numbers from ends in python
- Program to find possible number of palindromes we can make by trimming string in Python
- Program to make target by removing from first or last and inserting again in Python
- Program to find maximum price we can get by holding items into a bag in Python
- Removing nth character from a string in Python program
- Program to check one string can be converted to another by removing one element in Python
- Program to check we can cross river by stones or not in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

"10100101", 3, 2

11

Advertisements