Maximize cost obtained by removal of substrings “pr” or “rp” from a given String

Given a string str and two integers X and Y, the task is to find the maximum cost required to remove all the substrings “pr” and “rp” from the given string, where removal of substrings “rp” and “pr” costs X and Y respectively.

Examples:

Input: str = “abppprrr”, X = 5, Y = 4 
Output: 15 
Explanation: 
Following operations are performed: 
“abppprrr” -> “abpprr”, cost = 5 
“abpprr” -> “abpr”, cost = 10 
“abpr” -> “ab”, cost = 15 
Therefore, the maximized cost is 15

Input: str = “prprprrp”, X = 7, Y = 10 
Output: 37

Approach: The problem can be solved using the Greedy Approach. The idea here is to remove “pr” if X is greater than Y or remove “rp” otherwise. Follow the steps below to solve the problem.

  1. If X < Y: Swap the value of X and Y and replace the character ‘p’ to ‘r’ and vice versa in the given string.
  2. Initialize two variables countP and countR to store the count of ‘p’ and ‘r’ in the string respectively.
  3. Iterate over the array arr[] and perform the steps below: 
    • If str[i] = ‘p’: Increment the countP by 1.
    • If str[i] = ‘r’: Check the value of countP. If countP > 0, then increment the result by X and decrement the value of countP by 1. Otherwise, increment the value of countR by 1.
    • If str[i] != ‘p’ and str[i]!=’r’: Increment the result by min(countP, countR) * Y.
  4. Increment the result by min(countP, countR) * Y.
  5. Finally, after the removal of all the required substrings, print the result obtained.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to maintain the case, X>=Y
bool swapXandY(string& str, int X, int Y)
{
 
    int N = str.length();
 
    // To maintain X>=Y
    swap(X, Y);
 
    for (int i = 0; i < N; i++) {
 
        // Replace 'p' to 'r'
        if (str[i] == 'p') {
            str[i] = 'r';
        }
 
        // Replace 'r' to 'p'.
        else if (str[i] == 'r') {
            str[i] = 'p';
        }
    }
}
 
// Function to return the maximum cost
int maxCost(string str, int X, int Y)
{
    // Stores the length of the string
    int N = str.length();
 
    // To maintain X>=Y.
    if (Y > X) {
        swapXandY(str, X, Y);
    }
 
    // Stores the maximum cost
    int res = 0;
 
    // Stores the count of 'p'
    // after removal of all "pr"
    // substrings up to str[i]
    int countP = 0;
 
    // Stores the count of 'r'
    // after removal of all "pr"
    // substrings up to str[i]
    int countR = 0;
 
    // Stack to maintain the order of
    // characters after removal of
    // substrings
    for (int i = 0; i < N; i++) {
 
        if (str[i] == 'p') {
            countP++;
        }
        else if (str[i] == 'r') {
 
            // If substring "pr"
            // is removed
            if (countP > 0) {
                countP--;
 
                // Increase cost by X
                res += X;
            }
            else
                countR++;
        }
        else {
 
            // If any substring "rp"
            // left in the Stack
            res += min(countP, countR) * Y;
            countP = 0;
            countR = 0;
        }
    }
 
    // If any substring "rp"
    // left in the Stack
    res += min(countP, countR) * Y;
    return res;
}
 
// Driver Code
int main()
{
    string str = "abppprrr";
    int X = 5, Y = 4;
    cout << maxCost(str, X, Y);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to maintain the case, X>=Y
static boolean swapXandY(char []str, int X, int Y)
{
    int N = str.length;
 
    // To maintain X>=Y
    X = X + Y;
    Y = X - Y;
    X = X - Y;
 
    for(int i = 0; i < N; i++)
    {
 
        // Replace 'p' to 'r'
        if (str[i] == 'p')
        {
            str[i] = 'r';
        }
 
        // Replace 'r' to 'p'.
        else if (str[i] == 'r')
        {
            str[i] = 'p';
        }
    }
    return true;
}
 
// Function to return the maximum cost
static int maxCost(String str, int X, int Y)
{
     
    // Stores the length of the String
    int N = str.length();
 
    // To maintain X>=Y.
    if (Y > X)
    {
        swapXandY(str.toCharArray(), X, Y);
    }
 
    // Stores the maximum cost
    int res = 0;
 
    // Stores the count of 'p'
    // after removal of all "pr"
    // subStrings up to str[i]
    int countP = 0;
 
    // Stores the count of 'r'
    // after removal of all "pr"
    // subStrings up to str[i]
    int countR = 0;
 
    // Stack to maintain the order of
    // characters after removal of
    // subStrings
    for(int i = 0; i < N; i++)
    {
        if (str.charAt(i) == 'p')
        {
            countP++;
        }
        else if (str.charAt(i) == 'r')
        {
             
            // If subString "pr"
            // is removed
            if (countP > 0)
            {
                countP--;
 
                // Increase cost by X
                res += X;
            }
            else
                countR++;
        }
        else
        {
 
            // If any subString "rp"
            // left in the Stack
            res += Math.min(countP, countR) * Y;
            countP = 0;
            countR = 0;
        }
    }
 
    // If any subString "rp"
    // left in the Stack
    res += Math.min(countP, countR) * Y;
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "abppprrr";
    int X = 5, Y = 4;
     
    System.out.print(maxCost(str, X, Y));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to maintain the case, X>=Y
def swapXandY(str, X, Y):
 
    N = len(str)
 
    # To maintain X>=Y
    X, Y = Y, X
 
    for i in range(N):
 
        # Replace 'p' to 'r'
        if(str[i] == 'p'):
            str[i] = 'r'
 
        # Replace 'r' to 'p'.
        elif(str[i] == 'r'):
            str[i] = 'p'
 
# Function to return the maximum cost
def maxCost(str, X, Y):
 
    # Stores the length of the string
    N = len(str)
 
    # To maintain X>=Y.
    if(Y > X):
        swapXandY(str, X, Y)
 
    # Stores the maximum cost
    res = 0
 
    # Stores the count of 'p'
    # after removal of all "pr"
    # substrings up to str[i]
    countP = 0
 
    # Stores the count of 'r'
    # after removal of all "pr"
    # substrings up to str[i]
    countR = 0
 
    # Stack to maintain the order of
    # characters after removal of
    # substrings
    for i in range(N):
        if(str[i] == 'p'):
            countP += 1
 
        elif(str[i] == 'r'):
 
            # If substring "pr"
            # is removed
            if(countP > 0):
                countP -= 1
 
                # Increase cost by X
                res += X
 
            else:
                countR += 1
 
        else:
             
            # If any substring "rp"
            # left in the Stack
            res += min(countP, countR) * Y
            countP = 0
            countR = 0
 
    # If any substring "rp"
    # left in the Stack
    res += min(countP, countR) * Y
 
    return res
 
# Driver Code
str = "abppprrr"
X = 5
Y = 4
 
# Function call
print(maxCost(str, X, Y))
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to maintain the case, X>=Y
static bool swapXandY(char []str,
                      int X, int Y)
{
    int N = str.Length;
 
    // To maintain X>=Y
    X = X + Y;
    Y = X - Y;
    X = X - Y;
 
    for(int i = 0; i < N; i++)
    {
        // Replace 'p' to 'r'
        if (str[i] == 'p')
        {
            str[i] = 'r';
        }
 
        // Replace 'r' to 'p'.
        else if (str[i] == 'r')
        {
            str[i] = 'p';
        }
    }
    return true;
}
 
// Function to return the
// maximum cost
static int maxCost(String str,
                   int X, int Y)
{   
    // Stores the length of the String
    int N = str.Length;
 
    // To maintain X>=Y.
    if (Y > X)
    {
        swapXandY(str.ToCharArray(),
                  X, Y);
    }
 
    // Stores the maximum cost
    int res = 0;
 
    // Stores the count of 'p'
    // after removal of all "pr"
    // subStrings up to str[i]
    int countP = 0;
 
    // Stores the count of 'r'
    // after removal of all "pr"
    // subStrings up to str[i]
    int countR = 0;
 
    // Stack to maintain the order of
    // characters after removal of
    // subStrings
    for(int i = 0; i < N; i++)
    {
        if (str[i] == 'p')
        {
            countP++;
        }
        else if (str[i] == 'r')
        {           
            // If subString "pr"
            // is removed
            if (countP > 0)
            {
                countP--;
 
                // Increase cost by X
                res += X;
            }
            else
                countR++;
        }
        else
        {
            // If any subString "rp"
            // left in the Stack
            res += Math.Min(countP,
                            countR) * Y;
            countP = 0;
            countR = 0;
        }
    }
 
    // If any subString "rp"
    // left in the Stack
    res += Math.Min(countP,
                    countR) * Y;
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "abppprrr";
    int X = 5, Y = 4;   
    Console.Write(maxCost(str, X, Y));
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output: 

15



Time Complexity:O(N), where N denotes the length of the string
Auxiliary Space:O(1)

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.