# Maximum even length sub-string that is permutation of a palindrome in C++

C++Server Side ProgrammingProgramming

## Problem statement

Given a string the task is to find the maximum length of the sub-string of that can be arranged into a Palindrome.

## Example

If input string = “5432112356” then answer is 6 as maximum palindrome substring is “321123” and its length is 6

## Algorithm

• If the length of the sub-string is odd, then it cannot be considered in the final solutions.
• If the length of the sub-string is even, then it can be a possible solution only if each character in that sub-string occurs even number of times which can be done using the dictionary count. We check if each character occurs even number of times or not. If yes, then we include it as one of the possible solutions. Then we form the next sub-string by including the next character in the string which can be done by simply incrementing end and check recursively if a sub-string with greater length can be formed which satisfies the given conditions and return the maximum of all possible solutions

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> countt;
bool isPalindromePossible(unordered_map<int, int> &countt) {
for (auto key : countt) {
if (key.second & 1) {
return false;
}
return true;
}
int getMaxPalindrome(string str, unordered_map<int, int> &countt, int start, int end) {
if (end == str.length()) {
if ((end - start) % 2 == 0)
if (isPalindromePossible(countt))
return end - start;
return 0;
} else {
if ((end - start) % 2 == 0) {
if (isPalindromePossible(countt)) {
countt[str[end]]++;
return max(end - start, getMaxPalindrome(str, countt, start, end + 1));
} else {
countt[str[end]]++;
return getMaxPalindrome(str, countt, start, end + 1);
}
} else {
countt[str[end]]++;
unordered_map<int, int>
c(countt.begin(), countt.end());
int length = getMaxPalindrome(str, c, start, end + 1);
countt[str[end]]--;
countt[str[start]]--;
return max(length, getMaxPalindrome(str, countt, start + 1, end));
}
}
}
int main(int argc, char const *argv[]) {
string str = "5432112356";
int start = 0, end = 0;
cout << "Maximum palindrome length = " << getMaxPalindrome(str, countt, start, end) << endl;
return 0;
}

## Output

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

Maximum palindrome length = 6
Published on 10-Jan-2020 11:45:30