Program to find how max score we can get by removing 10 or 01 from binary string in Python

Suppose we have a binary string s and two values zero_one and one_zero. We can delete any substring "01" and receive zero_one points, or remove any substring "10" and receive one_zero points. We need 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. We can remove "01" three times to get 3×3 = 9 points. Then the remaining string is "10". By removing this we get another 2 points, so the total is 11.

Algorithm

To solve this, we will follow these steps ?

  • Convert the binary string to a list of integers

  • If zero_one

  • Use a stack to greedily remove "01" patterns first (higher priority)

  • Count remaining "10" patterns and add their points

Example

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 one_zero gives more points, prioritize "10" by swapping and flipping bits
        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 = []
        
        # Greedily remove "01" patterns using stack
        for x in A:
            if stack and stack[-1] < x:  # Found "01" pattern
                stack.pop()
                ans += zero_one
            else:
                stack.append(x)
        
        # Count remaining "10" patterns in stack
        ans += one_zero * min(stack.count(0), stack.count(1))
        return ans

# Test the solution
ob = Solution()
s = "10100101"
zero_one = 3
one_zero = 2
print(ob.solve(s, zero_one, one_zero))

The output of the above code is ?

11

How It Works

The algorithm uses a greedy approach with a stack:

  1. Priority Optimization: We always prioritize the pattern that gives more points by swapping values if needed

  2. Stack Processing: When we encounter a '1' after a '0' in the stack, we found an "01" pattern and remove it immediately

  3. Remaining Pairs: After processing all "01" patterns, we count the minimum of remaining 0s and 1s to form "10" patterns

Step-by-Step Trace

For s = "10100101", zero_one = 3, one_zero = 2:

  • A = [1,0,1,0,0,1,0,1]

  • Since zero_one > one_zero, no swapping needed

  • Process with stack: Remove three "01" patterns ? 9 points

  • Remaining stack: [1,0] ? Remove one "10" pattern ? 2 points

  • Total: 9 + 2 = 11 points

Conclusion

This greedy algorithm efficiently maximizes points by prioritizing the higher-value pattern first using a stack-based approach. The time complexity is O(n) where n is the length of the binary string.

Updated on: 2026-03-25T13:42:17+05:30

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements