Maximum score possible by removing substrings made up of single distinct character

Given a binary string S and an array A[], both of size N, the task is to find the maximum score possible by removing substrings of any length, say K, consisting of the same characters, and adding A[K] to the score. 
Examples:

Input: S = “abb”, A = [1, 3, 1]Output: 4Explanation: Initially, score = 0 and S=”abb” Remove the substring {S[1], .. S[2]}, of length 2, and add A[2] to score. Therefore, S modifies to “a”. Score = 3.Remove the substring {S[0]},  of length 1, and add A[1] to score. Therefore, S modifies to “”. Score = 4.
Input: S = “abb”, A = [2, 3, 1]Output: 6Explanation:Initially, score = 0 and S=”abb”.Remove the substring {S[2]}, of length 1, and add A[1] to score. Therefore, S modifies to “ab”. Score = 1Remove the substring {S[1]}, of length 1, and add A[1] to score. Therefore, S modifies to “a”. Score = 4Remove the substring {S[0]}, of length 1, and add A[1] to score. Therefore, S modifies to “”. Score = 6

Naive Approach: The simplest idea is to solve this problem is to use Recursion. Iterate over the characters of the string. If a substring consisting only of one distinct character is encountered, then proceed with either to continue the search or to remove the substring and recursively call the function for the remaining string. Below is the implementation of the above approach:

Python3

  

def isUnique(s):
    return True if len(set(s)) == 1 else False
  

def maxScore(s, a):
    n = len(s)
  
    
    if n == 0:
        return 0
  
    
    if n == 1:
        return a[0]
  
    
    mx = -1
  
    
    
    
    for i in range(n):
        for j in range(i, n):
  
            
            sub = s[i:j + 1]
  
            
            
            if isUnique(sub):
                mx = max(mx, a[len(sub)-1]
                         + maxScore(s[:i]+s[j + 1:], a))
  
        
    return mx
  
  

if __name__ == “__main__”:
  
    s = “011”
    a = [1, 3, 1]
    print(maxScore(s, a))

Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Memoization to store the result of the recursive calls and use Two pointer technique to store the substring consisting only of 1 distinct character.Follow the steps below to solve the problem:
Declare a recursive function that takes the string as input to find the required result.
Initialize an array, say dp[] to memoize the results.
If the value is already stored in the array dp[], return the result.
Otherwise, perform the following steps:
Considering the base case if the size of the string is 0, return 0. If it is equal to 1, return A[1].
Initialize a variable, say res, to store the result of the current function call.
Initialize two pointers, say head and tail, denoting the starting and ending indices of the substring.
Generate substrings satisfying the given condition, and for each substring, recursively call the function for the remaining string. Store the maximum score in res.
Store the result in the dp[] array and return it.

Print the value returned by the function as the result.

Below is the implementation of the above approach:

Python3

  

dp = dict()
  

def maxScore(s, a):
  
    
    if s in dp:
        return dp[s]
  
    
    n = len(s)
      
    
    if n == 0:
        return 0
        
    
    if n == 1:
        return a[0]
  
    
    head = 0
  
    
    mx = -1
  
    
    
    while head < n:         tail = head         while tail < n:                                                      if s[tail] != s[head]:                                                                      head = tail                 break                                         sub = s[head:tail + 1]                             mx = max(mx, a[len(sub)-1]                       + maxScore(s[:head] + s[tail + 1:], a))                             tail += 1         if tail == n:             break             dp[s] = mx     return mx       if __name__ == "__main__":          s = "abb"     a = [1, 3, 1]        print(maxScore(s, a)) 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.