Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively.
Input: S = “12333444”, X = 5, Y = 4, P = “34”
Below are the operations to remove substring to get the maximum cost:
- Remove the string “34″ from the string S. Therefore, the string S modifies to “123344”. Cost = 5.
- Remove the string “34″ from the string S. Therefore, the string S modifies to “1234”. Cost = 5.
- Remove the string “34″ from the string S. Therefore, the string S modifies to “12”. Cost = 5.
Therefore, the total cost is 5 + 5 + 5 = 15.
Input: S = “12121221”, X = 7, Y = 10, P = “12”
- Initialize a variable, say ans as 0 to store the maximum cost of removing the given substrings.
- Initialize a Stack that is used to decide whether the string P or the reverse of P is removed.
- Traverse the given string S and perform the following steps:
- Similarly, the reverse of the string P can be removed from any string by adding Y to the cost.
- Now, If X is greater than Y, then removing P before removing the reverse of P will give a greater value. Otherwise, remove the reverse of the pattern P first.
- After completing the above steps, print the value of ans as the total maximum cost.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.