Here's a C++ code that uses recursion to find the maximum length of a concatenated string with unique characters:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int maxLengthUtil(vector<string>& arr, string curr, int index) {
if (index == arr.size()) {
// Base case: all strings have been processed
// Check if the current string has unique characters
if (unordered_set<char>(curr.begin(), curr.end()).size() == curr.length())
return curr.length();
else
return 0;
}
// Exclude the current string
int exclude = maxLengthUtil(arr, curr, index + 1);
// Include the current string if it doesn't have duplicate characters
if (unordered_set<char>(curr.begin(), curr.end()).size() == curr.length())
curr += arr[index];
int include = maxLengthUtil(arr, curr, index + 1);
// Return the maximum length obtained by excluding or including the current string
return max(exclude, include);
}
int maxLength(vector<string>& arr) {
string curr = "";
int index = 0;
return maxLengthUtil(arr, curr, index);
}
int main() {
vector<string> arr = {"un", "iq", "ue"};
int maxLen = maxLength(arr);
cout << "Maximum length of a concatenated string with unique characters: " << maxLen << endl;
return 0;
}
Output:
Maximum length of a concatenated string with unique characters: 4
Explanation:
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|