Open In App

Maximizing ABCD Occurrences in a String

Last Updated : 17 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S containing capital letters A, B, C, and D. You can choose a subsequence, that makes an occurrence of ABCD by combining all the letters of that subsequence and removing it, the task is to output the maximum number of times the operation can be applied, If in each operation subsequences are removed optimally.

Examples:

Input: S = ABACBCAADBCD
Output: 2
Explanation:

  • First operation: Choose subsequence with indices {0, 1, 3, 8}. This subsequence makes an occurrence of ABCD and removes it. After that S = ABCAABCD
  • Second operation: Choose subsequence with indices {0, 1, 2, 8}. This subsequence makes another occurrence of ABCD and remove it. After that S = AABC

No more operations can be applied. Thus, 2 is the maximum number of times this operation cam be applied.

Input: S = ABDCA
Output: 0
Explanation: It can be verified that, It is not possible to apply operation.

Approach: Implement the idea below to solve the problem:

The problem is based on the observation. This is the simple HashMap problem, just see the frequency of previous character for counting the frequency of current character in order of ABCD. The frequency of current character should be counted only and only if previous character has greater frequency than current. For example, for counting frequency of B, A’s frequency must be greater and For counting frequency of C, B’s frequency must be greater than C and so on..

Steps were taken to solve the problem:

  • Declare a HashMap let say map to count the frequencies of characters.
  • Traverse on S an follow the below mentioned steps under the scope of loop:
    • If (current_char == A),then Increase the frequency of A in map.
    • Else If (current_char == B)
      • If (frequency of A > frequency of B), then increase the frequency of B in map.
    • Else If (current_char == C)
      • If (frequency of B > frequency of C), then increase the frequency of C in map.
    • Else If (current_char == D)
      • If (frequency of C > frequency of D), then increase the frequency of D in map.
  • Output the frequency of D stored in map.

Below is the implementation of the above approach:

C++




// C++ code to imlement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum operations
void max_operations(string s)
{
    // Declare an unordered map for counting frequencies
    unordered_map<char, int> mp;
 
    // Initialize initial values to avoid null pointer error
    mp['A'] = 0;
    mp['B'] = 0;
    mp['C'] = 0;
    mp['D'] = 0;
 
    // Loop for iterating over the string and applying the
    // logic
    for (char i : s) {
        if (i == 'A') {
            mp[i]++;
        }
        else if (i == 'B') {
            if (mp['A'] > mp['B']) {
                mp[i]++;
            }
        }
        else if (i == 'C') {
            if (mp['B'] > mp['C']) {
                mp[i]++;
            }
        }
        else if (i == 'D') {
            if (mp['C'] > mp['D']) {
                mp[i]++;
            }
        }
    }
 
    // Printing the maximum operations
    cout << mp['D'] << endl;
}
 
int main()
{
    // Input String
    string s = "ABACBCAADBCD";
 
    // Function call
    max_operations(s);
 
    return 0;
}


Java




// Java Code to implement the approach
 
import java.io.*;
import java.lang.*;
import java.util.*;
 
class Main {
    // Driver Function
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Input String
        String s = "ABACBCAADBCD";
 
        // Function call
        max_operations(s);
    }
    public static void max_operations(String s)
    {
 
        // Declared HashMap for
        // counting frequencies
        HashMap<Character, Integer> mp = new HashMap<>();
 
        // Initilaize initial values
        // to avoid null pointer error
        mp.put('A', 0);
        mp.put('B', 0);
        mp.put('C', 0);
        mp.put('D', 0);
 
        // Loop for iterating over
        // String and applying
        // the discussed logic
        for (char i : s.toCharArray()) {
            if (i == 'A') {
                mp.put(i, mp.getOrDefault(i, 0) + 1);
            }
            else if (i == 'B') {
                if (mp.get('A') > mp.get('B')) {
                    mp.put(i, mp.getOrDefault(i, 0) + 1);
                }
            }
            else if (i == 'C') {
                if (mp.get('B') > mp.get('C')) {
                    mp.put(i, mp.getOrDefault(i, 0) + 1);
                }
            }
            else if (i == 'D') {
                if (mp.get('C') > mp.get('D')) {
                    mp.put(i, mp.getOrDefault(i, 0) + 1);
                }
            }
        }
 
        // Printing the maximum operations
        System.out.println(mp.get('D'));
    }
}


Python




# Function to calculate the maximum operations
def max_operations(s):
    # Declare a dictionary for counting frequencies
    mp = {
        'A': 0,
        'B': 0,
        'C': 0,
        'D': 0
    }
 
    # Loop for iterating over the string and applying the logic
    for i in s:
        if i == 'A':
            mp[i] += 1
        elif i == 'B':
            if mp['A'] > mp['B']:
                mp[i] += 1
        elif i == 'C':
            if mp['B'] > mp['C']:
                mp[i] += 1
        elif i == 'D':
            if mp['C'] > mp['D']:
                mp[i] += 1
 
    # Printing the maximum operations
    print(mp['D'])
 
# Input String
s = "ABACBCAADBCD"
 
# Function call
max_operations(s)


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to calculate the maximum operations
    static void MaxOperations(string s)
    {
        // Declare a dictionary for counting frequencies
        Dictionary<char, int> mp = new Dictionary<char, int>();
 
        // Initialize initial values to avoid null reference error
        mp['A'] = 0;
        mp['B'] = 0;
        mp['C'] = 0;
        mp['D'] = 0;
 
        // Loop for iterating over the string and applying the logic
        foreach (char i in s)
        {
            if (i == 'A')
            {
                mp[i]++;
            }
            else if (i == 'B')
            {
                if (mp['A'] > mp['B'])
                {
                    mp[i]++;
                }
            }
            else if (i == 'C')
            {
                if (mp['B'] > mp['C'])
                {
                    mp[i]++;
                }
            }
            else if (i == 'D')
            {
                if (mp['C'] > mp['D'])
                {
                    mp[i]++;
                }
            }
        }
 
        // Printing the maximum operations
        Console.WriteLine(mp['D']);
    }
 
    static void Main()
    {
        // Input String
        string s = "ABACBCAADBCD";
 
        // Function call
        MaxOperations(s);
    }
}
// This code is contributed by akshitaguprzj3


Javascript




// Function to calculate the maximum operations
function maxOperations(s) {
    // Declare an object to count frequencies
    const mp = {
        'A': 0,
        'B': 0,
        'C': 0,
        'D': 0
    };
 
    // Loop for iterating over the string and applying the logic
    for (let i = 0; i < s.length; i++) {
        if (s[i] === 'A') {
            mp[s[i]]++;
        } else if (s[i] === 'B') {
            if (mp['A'] > mp['B']) {
                mp[s[i]]++;
            }
        } else if (s[i] === 'C') {
            if (mp['B'] > mp['C']) {
                mp[s[i]]++;
            }
        } else if (s[i] === 'D') {
            if (mp['C'] > mp['D']) {
                mp[s[i]]++;
            }
        }
    }
 
    // Printing the maximum operations
    console.log(mp['D']);
}
 
// Driver code
const s = "ABACBCAADBCD";
 
// Function call
maxOperations(s);


Output

2




Time Complexity: O(S.length())
Auxiliary Space: ~O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads