Program to count maximum score from removing substrings in Python


Suppose we have a string s and two values x and y. We can perform given two types of operations any number of times.

  • Search substring "ab", if present, then we can gain x points by removing it.

  • Search substring "ba", if present, then we can gain y points by removing it.

We have to find maximum points we can gain after applying the above operations on s.

So, if the input is like s = "cbbaacdeabb" x = 4 y = 5, then the output will be 14 because initial string is "cbbaacdeabb", then remove "cbbaacde(ab)b" to get 4, now string is "cbbaacdeb", then remove "cb(ba)acdeb" to get more 5, so current score 4+5 = 9, now string is "cbacdeb", then again remove "c(ba)cdeb", to get extra 5 so current score 9+5=14, and string is "ccdeb", now there is nothing to remove next.

To solve this, we will follow these steps −

  • a := 'a', b := 'b'
  • ans := 0, a_st := 0, b_st := 0
  • if y > x, then
    • swap a and b
    • swap x and y
  • for each c in s, do
    • if c is same as a, then
      • a_st := a_st + 1
    • otherwise when c is same as b, then
      • if a_st is non-zero, then
        • ans := ans + x
        • a_st := a_st - 1
      • otherwise,
        • b_st += 1
    • otherwise,
      • ans := ans + y * minimum of a_st and b_st
      • a_st := 0
      • b_st := 0
  • return ans + y * minimum of a_st and b_st

Example

Let us see the following implementation to get better understanding −

def solve(s, x, y):
   a = 'a'
   b = 'b'
   ans = 0
   a_st = 0
   b_st = 0
   if y > x:
      a,b = b,a
      x,y = y,x
   for c in s:
      if c == a:
         a_st += 1
      elif c == b:
         if a_st:
            ans += x
            a_st -= 1
         else: b_st += 1
      else:
         ans += y * min(a_st, b_st)
         a_st = 0
         b_st = 0
   return ans + y * min(a_st, b_st)

s = "cbbaacdeabb"
x = 4
y = 5
print(solve(s, x, y))

Input

"cbbaacdeabb", 4, 5

Output

14

Updated on: 06-Oct-2021

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements