# Maximum weight transformation of a given string in C++

C++Server Side ProgrammingProgramming

## Problem statement

Given a string consisting of only A’s and B’s. We can transform the given string to another string by toggling any character. Thus many transformations of the given string are possible. The task is to find the Weight of the maximum weight transformation.

Weight of a sting is calculated using below formula −

Weight of string = Weight of total pairs + weight of single characters - Total number of toggles.
• Two consecutive characters are considered a pair only if they are different.

• Weight of a single pair (both characters are different) = 4

• Weight of a single character = 1

If the input string is − "AA" then the output will be 3 −

• Transformations of the given string are "AA", "AB", "BA" and "BB".

• Maximum weight transformation is "AB" or "BA". And weight is "One Pair - One Toggle" = 4-1 = 3.

## Algorithm

1. If (n == 1)
maxWeight(str[0..n-1]) = 1
2. Else If str != str
maxWeight(str[0..n-1]) = Max (1 + maxWeight(str[1..n-1]), 4 + getMaxRec(str[2..n-1])
3. Elses
maxWeight(str[0..n-1]) = Max (1 + maxWeight(str[1..n-1]), 3 + getMaxRec(str[2..n-1])

## Example

#include<bits/stdc++.h>
using namespace std;
int getMaxRec(string &str, int i, int n, int lookup[]){
if (i >= n) {
return 0;
}
if (lookup[i] != -1) {
return lookup[i];
}
int ans = 1 + getMaxRec(str, i + 1, n, lookup);
if (i + 1 < n) {
if (str[i] != str[i+1]) {
ans = max(4 + getMaxRec(str, i + 2, n, lookup), ans);
} else {
ans = max(3 + getMaxRec(str, i + 2, n, lookup), ans);
}
}
return lookup[i] = ans;
}
int getMaxWeight(string str){
int n = str.length();
int lookup[n];
memset(lookup, -1, sizeof lookup);
return getMaxRec(str, 0, str.length(), lookup);
}
int main(){
string str = "AA";
cout << "Result = " << getMaxWeight(str) << endl;
return 0;
}

## Output

When you compile and execute the above program. It generates the following output −

Result = 3