The Maximum Score Possible by Removing Substrings made up of Single Distinct Character


The maximum score possible by removing substrings made up of a single distinct character is a well-known problem in the field of computer science and algorithm design. The problem statement involves finding the optimal solution to remove all the contiguous substrings from a binary string that contains only one type of character and score points for every removed substring of length K, where K can vary for each substring. This problem has various real-life applications, including text analysis and compression.

In this tutorial, we will provide a solution to this problem using C++, and explain the logic behind our algorithm. We will also discuss the time and space complexity of our solution and provide a step-by-step guide on how to implement it. So let's dive in!

Problem Statement

The problem requires finding the highest score that can be achieved by deleting contiguous substrings of any length from a binary string S, where each deleted substring contains only the same character. The array A of size N contains scores for substrings of each length, and the score for a deleted substring of length K is A[K].

Sample Example 1

Input

A binary string 
S is given as "abb" and an array A is given as [2, 3, 1].

Output

A score of 6 can be achieved by removing substrings composed of 
identical characters, resulting in the maximum attainable score.

Explanation: Initially, with a score of 0 and the string "abb", we remove the substring at index 2, which has a length of 1, and increment the score by the corresponding value from the array. As a result, the string becomes "ab" and the score increases to 1. Next, we remove the substring at index 1, add its corresponding value to the score, and modify the string to "a". The score then becomes 4. Finally, we remove the substring at index 0, add the corresponding value to the score, and update the string to an empty string. The final score is 6.

Sample Example 2

Input

A binary string S is given as "abb" and an array A is given as [1, 3, 1].

Output

A score of 4 can be achieved by eliminating substrings composed of 
identical characters, resulting in the maximum possible score.

Explanation: Starting with a score of 0, the initial string "abb" undergoes substring removal. Specifically, the substring "bb" is removed, increasing the score by the corresponding value in the array A, resulting in a modified string "a" and a score of 3. Subsequently, the remaining character "a" is removed, adding A[1] to the score, resulting in an empty string and a final score of 4. This process exemplifies how the program calculates the maximum achievable score by strategically removing substrings from the input string.

Algorithm

1. Start by including the necessary header files: ‘iostream’, ‘vector’, ‘map’, and ‘algorithm’.

2. Declare a ‘std::map’ named ‘dp’ to store precomputed results.

3. Define a function ‘calculateMaximumScore’ that takes a string ‘str’ and a vector of integers ‘nums’ as input and returns an integer.

4. Within the ‘calculateMaximumScore’ function:

  • Check if the string ‘str’ is present in the ‘dp’ map. If found, return the corresponding value.

  • Calculate the length of the input string ‘str’ and store it in the variable ‘len’.

  • If the length of the string is 0, return 0.

  • If the length of the string is 1, return the first element of the ‘nums’ vector.

  • Initialize the variable ‘start’ to 0 and ‘maxScore’ to -1.

  • Start a loop with ‘start’ as the loop variable and iterate while ‘start’ is less than ‘len’.

    • Within the loop, initialize another variable ‘end’ to ‘start’.

    • Start an inner loop with ‘end’ as the loop variable and iterate while ‘end’ is less than ‘len’.

      • Check if the character at the index ‘end’ is different from the character at the index ‘start’ in the string ‘str’.

      • Create a substring ‘sub’ by extracting the characters from the index ‘start’ to the index ‘end’ from the string ‘str’.

      • Calculate the maximum score by adding the value at index ‘sub.size() - 1’ from the ‘nums’ vector with the result of recursively calling the ‘calculateMaximumScore’ function on the modified string ‘str’ obtained by concatenating the substrings before and after ‘start’ and ‘end’ respectively.

      • Update the ‘maxScore’ with the maximum of the current ‘maxScore’ and the calculated score.

      • Increment ‘end’ by 1.

    • Check if ‘end’ is equal to ‘len’. If true, break out of the outer loop.

    • Increment ‘start’ by 1.

    5. In the ‘main’ function:

  • Declare a string variable ‘inputStr’ and initialize it with the input string "abb".

  • Declare a vector of integers ‘inputNums’ and initialize it with the input values {2, 3, 1}.

  • Call the ‘calculateMaximumScore’ function with ‘inputStr’ and ‘inputNums’ as arguments, and output the result.

The algorithm outlines the steps performed by the program to calculate the maximum score by removing substrings based on the given input string and vector of numbers.

Example

Implementation of the above algorithm using C++

The below C++ program implements a dynamic programming approach to calculate the maximum score achievable by removing substrings from a given string. It utilizes memoization to store precomputed results and optimizes the recursion by breaking down the problem into smaller subproblems. By iteratively examining different substrings, it determines the maximum score by considering the removal of each substring and recursively calculating the score for the modified string.

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

std::map<std::string, int> dp;
int calculateMaximumScore(std::string str, std::vector<int> nums) {
   if (dp.find(str) != dp.end()) {
      return dp[str];
   }
   int len = str.size();
   if (len == 0) {
      return 0;
   }
   if (len == 1) {
      return nums[0];
   }
   int start = 0;
   int maxScore = -1;
   while (start < len) {
      int end = start;
      while (end < len) {
         if (str[end] != str[start]) {
            start = end;
            break;
         }
         std::string sub = str.substr(start, end - start + 1);
         maxScore = std::max(maxScore, nums[sub.size() - 1] +
            calculateMaximumScore(str.substr(0, start) +
            str.substr(end + 1), nums));
         end += 1;
      }
      if (end == len) {
         break;
      }
   }
   dp[str] = maxScore;
   return maxScore;
}
int main() {
   std::string inputStr = "abb";
   std::vector<int> inputNums = {2, 3, 1};
   std::cout << "The maximum score possible by removing substrings made up of single distinct character: " << calculateMaximumScore(inputStr, inputNums);
   return 0;
}

Output

The maximum score possible by removing substrings made up of single distinct character: 6

Conclusion

To sum up, the provided C++ program effectively calculates the maximum achievable score by removing substrings composed of single distinct characters from a given string. By utilizing a dynamic programming approach and memoization, the program optimizes the computation by storing precomputed results. Through recursive exploration of different substrings, the program determines the optimal score by considering the removal of each substring and selecting the highest scoring path. The program provides a robust solution for maximizing the score by intelligently removing substrings from the input string.

Updated on: 08-Sep-2023

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements